PyQt4 创建一个简单的 GUI 应用程序时遇到问题 [英] PyQt4 trouble creating a simple GUI application

查看:42
本文介绍了PyQt4 创建一个简单的 GUI 应用程序时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

so I'm creating a simple windows application with Python and PyQt4. I've designed my UI the way I want it in QtCreator and I've created the necessary .py file from the .ui file. When I try to actually open an instance of the window however I'm given the following error:

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

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

So I go back into the ui_mainwindow.py file and comment out the following line:

MainWindow.setCentralWidget(self.centralWidget)

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

Now when I run main.py it will generate an instance of the window but it loses its grid layout and the UI elements just sort of float there. Any idea what I'm doing wrong?

我的 main.py 文件:

My main.py file:

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 文件:

and my window.py file:

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)

推荐答案

您需要从 QMainWindow 继承,而不是从 QWidget 继承.setCentralWidgetQMainWindow 的一个方法.

You need to inherit from QMainWindow, not QWidget. setCentralWidget is a method of QMainWindow.

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)

这篇关于PyQt4 创建一个简单的 GUI 应用程序时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆