【问题标题】:Wrong widget order using vbox layout PyQt使用 vbox 布局 PyQt 的小部件顺序错误
【发布时间】:2015-06-12 22:46:02
【问题描述】:

我正在尝试将 QLabel 小部件放在 QLineEdit 小部件编辑之上(即之前)。

但它一直出现在 QLineEdit 小部件之后。我的代码,

class CentralWidget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(CentralWidget, self).__init__(parent)

        # set layouts
        self.layout = QtGui.QVBoxLayout(self)

        # Flags
        self.randFlag = False        
        self.sphereFlag = False
        self.waterFlag = False

        # Poly names
        self.pNames = QtGui.QLabel("Import file name", self) # label concerned
        self.polyNameInput = QtGui.QLineEdit(self)           # line edit concerned

        # Polytype selection
        self.polyTypeName = QtGui.QLabel("Particle type", self)
        polyType = QtGui.QComboBox(self)
        polyType.addItem("")
        polyType.addItem("Random polyhedra")
        polyType.addItem("Spheres")
        polyType.addItem("Waterman polyhedra")
        polyType.activated[str].connect(self.onActivated)

        self.layout.addWidget(self.pNames)
        self.layout.addWidget(self.polyNameInput)
        self.layout.addWidget(self.pNames)
        self.layout.addWidget(self.polyTypeName)
        self.layout.addWidget(polyType)
        self.layout.addStretch()

    def onActivated(self, text):
        # Do loads of clever stuff that I'm not at liberty to share with you

class Polyhedra(QtGui.QMainWindow):

    def __init__(self):

        super(Polyhedra, self).__init__()

        self.central_widget = CentralWidget(self)
        self.setCentralWidget(self.central_widget)

        # Set up window        
        self.setGeometry(500, 500, 300, 300)
        self.setWindowTitle('Pyticle')
        self.show()

    # Combo box
    def onActivated(self, text):

        self.central_widget.onActivated(text)

def main():

    app = QtGui.QApplication(sys.argv)
    poly = Polyhedra()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

我得到的窗口在下面。

我错过了什么?我认为 QVbox 允许按照您将项目添加到主小部件的顺序垂直堆叠事物。 (这些子小部件对象是否称为小部件?)

【问题讨论】:

    标签: python widget pyqt


    【解决方案1】:

    问题是因为您在布局中添加了两次self.pNames 标签。

    #portion of your code
    ... 
    self.layout.addWidget(self.pNames)        # here 
    self.layout.addWidget(self.polyNameInput)
    self.layout.addWidget(self.pNames)         # and here
    self.layout.addWidget(self.polyTypeName)
    self.layout.addWidget(polyType)
    self.layout.addStretch()
    ...
    

    第一次添加 QLabel 时,它会添加到 LineEdit 之前,而当您第二次添加时,它会移动到 LineEdit 的底部。这是因为QLabel 只有一个对象,即self.pNames。它只能添加到一个位置。如果要使用两个标签,请考虑创建两个单独的QLabel 对象

    【讨论】:

    • 花了一个下午最好的时间来锻炼正在发生的事情。有时您需要第二双眼睛来指出明显的...谢谢
    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2022-01-02
    • 2018-08-14
    • 2017-09-06
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多