When reading through a PyQt4 tutorial, sometimes the examples uses QtGui.QMainWindow, sometimes it uses QtGui.QWidget.
Question: How do you tell when to use which?
import sys
from PyQt4 import QtGui
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.statusBar().showMessage('Ready')
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Statusbar')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Another code example:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
cb = QtGui.QCheckBox('Show title', self)
cb.move(20, 20)
cb.toggle()
cb.stateChanged.connect(self.changeTitle)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('QtGui.QCheckBox')
self.show()
def changeTitle(self, state):
if state == QtCore.Qt.Checked:
self.setWindowTitle('QtGui.QCheckBox')
else:
self.setWindowTitle('')
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
A QDialog is based on QWidget , but designed to be shown as a window. It will always appear in a window, and has functions to make it work well with common buttons on dialogs (accept, reject, etc.). QMainWindow is designed around common needs for a main window to have.
Qt Main Window Framework A main window provides a framework for building an application's user interface. Qt has QMainWindow and its related classes for main window management. QMainWindow has its own layout to which you can add QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar.
The QWidget class is the base class of all user interface objects. The widget is the atom of the user interface: it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a Z-order.
The QWidget widget is the base class of all user interface objects in PyQt5. We provide the default constructor for QWidget . The default constructor has no parent. A widget with no parent is called a window.
QMainWindow is a class that understands GUI elements like a
QWidget is just a raw widget.
When you want to have a main window for you project, use QMainWindow.
If you want to create a dialog box (modal dialog), use QWidget, or, more preferably, QDialog.
If you are not going to use a menu bar, tool bar or dock widgets, they are the same to you.
If you will use one of those, use QMainWindow. And don't forget to call setCentralWidget to your main layout widget.
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