我在Python2的QMainWindow中看不到QLabel和QLineEdit小部件

时间:2016-05-24 08:14:18

标签: qt python-2.7 pyside qlineedit qlabel

我编写了这段代码,我不明白为什么QLabel和QLineEdit不显示小部件?我必须把它们放在另一个班级吗?它是Python2.7和PySide。

这是我运行代码时窗口的样子:

enter image description here

#!/usr/bin/env python
# coding: utf-8

import sys
import crypt
from PySide import QtGui

class MyApp(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyApp, self).__init__(parent)
        self.initui()

    def initui(self):
        # main window size, title and icon
        self.setMinimumSize(500, 350)
        self.setWindowTitle("Calculate a password hash in Linux")

        # lines for entering data
        self.saltLabel = QtGui.QLabel("Salt:")
        self.saltLine = QtGui.QLineEdit()
        self.saltLine.setPlaceholderText("e.g. $6$xxxxxxxx")

        # set layout
        grid = QtGui.QGridLayout()
        grid.addWidget(self.saltLabel, 0, 0)
        grid.addWidget(self.saltLine, 1, 0)

        self.setLayout(grid)

        # show a widget
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    instance = MyApp()
    instance.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:2)

如何将QWidget用作centralWidget

widget = QWidget()
widget.setLayout(grid)
#add your widgets and...
self.setCentralWidget(widget)

,因为您在show()

中进行了调用,因此无需致电__main__

这取决于所有者,但我建议对QWidget进行子类化,并尽可能简洁地保留QMainWindow个实例。实施可以是:

class MyWidget(QtGui.QWidget):

    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        grid = QtGui.QGridLayout()
        #and so on...

并在widget个实例中将其用作QMainWindow。这大大提高了可读性,可维护性和可重用性:)