PyQt4 trouble creating a simple GUI application

2020-07-05 05:23发布

问题:

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'

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

MainWindow.setCentralWidget(self.centralWidget)

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?

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_())

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)

回答1:

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)


标签: python qt pyqt4