Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt4 trouble creating a simple GUI application

Tags:

python

qt

pyqt4

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)
like image 616
Cyborg771 Avatar asked Apr 18 '12 23:04

Cyborg771


People also ask

Is PyQt good for GUI?

PyQt is a Python binding for Qt, which is a set of C++ libraries and development tools that include platform-independent abstractions for Graphical User Interfaces (GUI), as well as networking, threads, regular expressions, SQL databases, SVG, OpenGL, XML, and many other powerful features.


1 Answers

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)
like image 190
Avaris Avatar answered Oct 14 '22 20:10

Avaris