【问题标题】:PyQt4 trouble creating a simple GUI applicationPyQt4 麻烦创建一个简单的 GUI 应用程序
【发布时间】:2012-04-30 10:53:00
【问题描述】:

所以我正在使用 Python 和 PyQt4 创建一个简单的 Windows 应用程序。我在 QtCreator 中按照我想要的方式设计了我的 UI,并且我已经从 .ui 文件创建了必要的 .py 文件。当我尝试实际打开一个窗口实例时,却出现以下错误:

AttributeError: 'Window' object has no attribute 'setCentralWidget'

所以我回到 ui_mainwindow.py 文件并注释掉以下行:

MainWindow.setCentralWidget(self.centralWidget)

现在,当我运行 main.py 时,它会生成一个窗口实例,但它会丢失它的网格布局,并且 UI 元素只是在那里浮动。知道我做错了什么吗?

我的 main.py 文件:

import sys
from PyQt4.QtGui import QApplication
from window import Window

if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

还有我的 window.py 文件:

from PyQt4.QtCore import Qt, SIGNAL
from PyQt4.QtGui import *

from ui_mainwindow import Ui_MainWindow

class Window(QWidget, Ui_MainWindow):

    def __init__(self, parent = None):

        QWidget.__init__(self, parent)
        self.setupUi(self)

【问题讨论】:

    标签: python qt pyqt4


    【解决方案1】:

    您需要继承自 QMainWindow,而不是 QWidgetsetCentralWidgetQMainWindow 的方法。

    from PyQt4.QtCore import Qt, SIGNAL
    from PyQt4.QtGui import *
    
    from ui_mainwindow import Ui_MainWindow
    
    class Window(QMainWindow, Ui_MainWindow):
        def __init__(self, parent = None):
    
            QMainWindow.__init__(self, parent)
            # or better
            # super(Window, self).__init__(parent)
    
            self.setupUi(self)
    

    【讨论】:

      猜你喜欢
      • 2012-02-03
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多