【问题标题】:I can't see QLabel and QLineEdit widgets in my QMainWindow in Python2我在 Python2 的 QMainWindow 中看不到 QLabel 和 QLineEdit 小部件
【发布时间】:2016-05-24 08:14:18
【问题描述】:

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

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

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

【问题讨论】:

  • 您不需要QMainWindow。您应该使用QDialog 或简单地使用QWidget

标签: qt python-2.7 pyside qlineedit qlabel


【解决方案1】:

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。这大大提高了可读性、可维护性和可重用性:)

【讨论】:

  • 好的,当我这样做时(自己不是这个),小部件确实显示但在左上角,一个在另一个。但是,我用 QWidget 切换了 QMainWindow ,现在可以了。谢谢!
  • 您是否尝试过更新的答案? setCentralWidget 应该填写您的 QMainWindow 实例。如果你不能让上面的例子工作,请让我更新。我也可以给出更详细的答案。
  • 我保留了 QMainWindow,在网格中添加了 QLabel 和 QLineEdit 小部件,并将小部件设置为 QMainWindow 中的中心。成功了,谢谢!
猜你喜欢
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 2018-09-10
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多