Introduction
In KeymouseGo Project, when building with pyinstaller -w, we need to offer a .py file describing the ui in a class form. However, we do not need to write it ourselves. We can generate the python file from a .ui file, which is eaily made with QT creator.
Generate UI Files for pyinstaller -w
QT creator is a powerful software, which is used to write a cpp project with GUI. However, in this project we only need the QT deigner part.
Install QT Creator
There is nothing special in the installation.
sudo apt update && sudo apt upgrade
sudo apt install qtcreator
After that, it could be opened in the application menu or simply by
qtcreator
Write a .ui File
Create a project according to the instruciton in QT creator and we will find a .ui file in the initial project, which can be opened in a GUI mode of QT designer instead of a lint format.
Editing the .ui file in QT design will directly generate the xml file.
Generate .py from .ui
Install uic package, which is used to generate python files describing UI from ui files.
pip install pyqode-uic
uic myui.ui -o myui.py
Function Files
However, only with files describing UI, there is no function on this UI. Therefore, function files are necessary. The function file create a subclass of view file, which is used to add several functions on each part of the ui. To be mentioned, decorators @classmethod and @slot.
ClassMethod
Decorator Classmethod can make this method can be directly used by the class instead of odinarily by the instance of the class.
class MyClass:
@classmethod
def method1(cls):
print("Class method called")
def method2(self):
print("Ordinary method called")
MyClass.method1() # Output: Class method called
my_instance = MyClass()
my_instance.method2() # Output: Ordinary method called
Slot(ScriptEvent)
Slot(ScriptEvent) is used to capture different operations on the ui, and the code below is an example for it.
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtScript import QScriptEngine
class MyButton(QPushButton):
def __init__(self):
super().__init__()
self.setText("Click me!")
@Slot(ScriptEvent)
def handleScriptEvent(self, event):
print(f"Received script event: {event.type()}")
button = MyButton()
# Connect the button to a script engine
script_engine = QScriptEngine()
script_engine.connect(button, &QPushButton::clicked, button.handleScriptEvent)
# Run the script
script_engine.evaluate("button.click()")