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

I can't see QLabel and QLineEdit widgets in my QMainWindow in Python2

我写了这段代码,但我不明白为什么 QLabel 和 QLineEdit 小部件没有出现?我必须将它们放在另一个 class 中吗?它是 Python2.7 和 PySide.

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

#!/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. $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()

如何使用 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...

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