使用 Qt Designer(生成的 GUI)创建自定义小部件并将它们提升为默认小部件

Creating custom widgets and promoting them to default ones using Qt Designer (generated GUI)

我正在尝试收集ui在我的工作中使用的自定义 QT 小部件库存。我想坚持使用 PySide2 和 QT Designer 进行布局开发。 我在使用设计器推广自定义小部件时也遇到了问题,它抛出:

"QFormBuilder was unable to create a custom widget of the 
class'MyCustomButton'; defaulting to base class 'QPushButton'."

我将 .ui 文件与 python 脚本一起保存。

小部件推广是这样完成的:

Base class name: QPushButton
Promoted class name: MyCustomButton
Header file: qt_widget_app.h

qt_widget_app.py

import sys

from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton
from PySide2.QtCore import QFile, QObject
from PySide2.QtUiTools import QUiLoader


class MyCustomButton(QPushButton):

    def __init__(self, parent=None):
        super(MyCustomButton, self).__init__(parent)
        self.hidden_value = "Really Unique Text"
        self.clicked.connect(self.on_click)

    def on_click(self):
        self.setText("Custom Button Clicked!")


class ExampleForm(QObject):

    def __init__(self, ui_file, parent=None):
        super(ExampleForm, self).__init__(parent)
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        self.window = loader.load(ui_file)
        ui_file.close()
        self.window.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = ExampleForm(ui_file='qt_widget_app.ui')
    sys.exit(app.exec_())

.py 和 .ui 文件可以在这里找到: https://gofile.io/?c=BUOjQE

我想我问得太快了(在深入 PySide2 文档之前):

解决方法是添加:

loader.registerCustomWidget(MyCustomButton)

在 ExampleForm 初始化方法中。