Reputation:
It seems like I have failed before I even started - I cannot get a GUI generated by Qt designer to launch in Python 3.
My setup:
Having looked through gazillion of tutorials (99% dedicated to Qt4 which is not compatible with Qt5), I have found the following code which is supposed to be the "hello world" implementation of a simple Qt GUI:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from blob import Ui_MainWindow
class AppWindow(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
app = QApplication(sys.argv)
w = AppWindow()
w.show()
sys.exit(app.exec_())
However, when I try to execute it in Jupyter Notebook, I get the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-1-804f20d6b17d> in <module>()
12
13 app = QApplication(sys.argv)
---> 14 w = AppWindow()
15 w.show()
16 sys.exit(app.exec_())
<ipython-input-1-804f20d6b17d> in __init__(self)
8 super().__init__()
9 self.ui = Ui_MainWindow()
---> 10 self.ui.setupUi(self)
11 self.show()
12
C:\Users\Dante\blob.py in setupUi(self, MainWindow)
18 self.label.setGeometry(QtCore.QRect(50, 20, 131, 16))
19 self.label.setObjectName("label")
---> 20 MainWindow.setCentralWidget(self.centralwidget)
21 self.menubar = QtWidgets.QMenuBar(MainWindow)
22 self.menubar.setGeometry(QtCore.QRect(0, 0, 545, 26))
AttributeError: 'AppWindow' object has no attribute 'setCentralWidget'
I haven't touched manually the blob.py.
Does anyone happen to know why the code generated by Qt Designer is buggy? Anything I have missed?
NB: launching a simple PyQt code (i.e. without importing the GUI, but creating it manually with a few commands) works fine.
Thank you for your kind help!
Upvotes: 1
Views: 3447
Reputation: 244282
When using Qt Designer a template is used (MainWindow, Dialog, Widget) and when implementing the logic should use the same widget. In your case you have used MainWindow, so you should use QMainWindow instead of QDialog. The following code is the solution:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from blob import Ui_MainWindow
class AppWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
app = QApplication(sys.argv)
w = AppWindow()
w.show()
sys.exit(app.exec_())
Upvotes: 2