使用vbox布局PyQt的错误窗口小部件顺序

时间:2015-06-12 22:46:03

标签: python widget pyqt

我正在尝试将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允许按照将项添加到主窗口小部件的顺序垂直堆叠。 (这些子窗口小部件对象是否称为窗口小部件?)

The window I get,

1 个答案:

答案 0 :(得分:2)

问题是因为您要在布局上添加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

的单独对象