General
Template
1 | class Window(QtWidgets.QMainWindow): |
Import Qt Modules
if you are using PyQt5
binding:
1 | from PyQt5 import QtCore, QtGui, QtWidgets |
if you are using PySide2
binding, here’s a wrapper I made which can
be found here.
I’m using Qt.py a Python 2 & 3 shim around all Qt bindings, it just saves a lot of work.
1 | from Qt import QtCore, QtGui, QtWidgets |
Using QApplication
Launch as standalone application using QApplication
, or if a QApplication
instance
exist, there’s no need to instantiate it. use QtWidgets.QApplication.instance()
to check
1 | if __name__ == '__main__': |
Close Event
Delete Widget when Closed
by default, closing the widget is hiding it not destroying the object
1 | {WindowObject}.setAttribute(QtCore.Qt.WA_DeleteOnClose) |
Unique Instance
Raise existing instance (for example: widgets that are hidden during closeEvent
);
if no instance is available, create a new one.
1 | def show(): |
Other
Register Style Sheet
1 | def show(): |
Register QResources
QtCore.QResource.registerResource(PATH_TO_RCC)
Maya
Parent to Maya’s Main Window
by default Qt window is not parented to Maya application
1 | from shiboken2 import wrapInstance |
Window Docking
Dockable Window
The widget/window can now be docked into Maya’s main window;
Auto-docking
The above example of auto-docking may not work for certain Maya builds
A workaround is to use the following method, but it only applies to QWidget
type not QMainWindow
type.
Instantiate Widget
When the UI has no parent (Maya main window), it will get instantly destroyed by the garbage collector, unless we keep an instance:
1 | # in the show function |
or using global variable to store the instance
1 | def show(): |
Close Application in Maya
1 | def show(): |
Error in PyCharm
When this error occurs, it is due to MayaDevKit environment MayaDevKit allows maya python command auto-completion, remove it from PyCharm
1 | app = QtWidgets.QApplication(sys.argv) |
Unreal Engine
1 | import unreal |
Raise Existing Instance
in the show()
we need to return the window instance and assign it to a global variable:
1 | # main.py |
in the parent python command call (this maybe an Unreal menu command)
1 | from test import main |
Override closeEvent()
To exit the Unreal Editor when Qt Window is closed:
1 | def closeEvent(self, event): |
To override at an instance level:
1 | import types |
Bonus:
PySide2 UI Loading
1 | from PySide2 import QtCore, QtWidgets |
Reference
Reddit - PyQt5 - Why do I get an Empty Window?
Stack Overflow - pycharm use pyside2 TypeError: ‘NoneType’ object is not callable