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)
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With