Python qt: windows
In Qt, any widget can be a window, simply by calling one of it's methods show()
or raise_()
.
Despite this, there are 2x classes that are built to be used primarilly as windows:
QtWidgets.QMainWindow()
QtWidgets.QDialog()
Modal vs Modeless
In UI terms, a Modal window is a window that interrupts the flow of execution, stealing the focus, and disallowing other windows from being interacted with until it is dismissed. Modal windows are displayed using the method
raise_()
A Modeless window is a normal window. You can start as many windows as you'd like, and you can use modeless windows alongside each other. Modeless windows are displayed using the method
show()
.
The two windows can be used together, but a modal window can only launch new modal windows.
Window Widgets
QWidget
QWidgets (any QWidget subclass) can be a window. Even if you have no production use-case for this, you'll find it invaluable for testing.
wid = QtWidgets.QPushButton('A Button') wid.show()QMainWindow
QMainWindows are a special type of widget that is intended to be used as a top-level window. All of the features of a QMainWindow can be reproduced in a QWidget, it exists solely for convenience. QMainWindows have builtin support for:
- menubar (file menu)
- toolbars (for actions - like photoshop)
- docking widgets (top, left, right, bottom)
- statusbar (mouseover notifications)
win = QtWidgets.QMainWindow() wid = QtWidgets.QLabel('Example Main Widget') win.setCentralWidget(wid) win.show()QDialog
QDialogs can be used like any other widget, but their intended purpose is for modal prompts that can be accepted/rejected. MessageBoxes, for example are QDialogs.
win = QtCore.QDialog() action = win.exec_() if action is QtWidgets.QDialog.Accepted: # do something elif action is QtWidgets.QDialog.Rejected: # do something elseQMessageBox
msgbox = QMessageBox() msgbox.setText("The document has been modified.") ## Main Text msgbox.setInformativeText("Do you want to save your changes?") ## Smaller SubText msgbox.setStandardButtons(QMessageBox.Save|QMessageBox.Discard|QMessageBox.Cancel) ## Buttons to display msgbox.setDefaultButton(QMessageBox.Save) action = msgBox.exec_() if msgbox.buttonRole(msgbox.clickedButton()) is QtWidgets.QMessageBox.ButtonRole.RejectRole: # do something ## Getting info from QMessageBox if action == QMessageBox.Save: # do something elif action == QMessageBox.Discard: # do something elif action == QMessageBox.Cancel: # do something
Useful Methods
widget.window() # get any widget's window (or None if is window) window.setAttribute(PySide.QtCore.Qt.WA_DeleteOnClose) # delete this window from memory on close window.resize(600, 300) window.setWindowTitle('My Window')