Search code examples
pythonpython-3.xqt-designerpyside2

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


I'm trying to build a stock of custom QT widgets used in my job. I want to stick to PySide2 and QT Designer for layout development. I have also experienced problems with promoting custom widgets using designer, it throws:

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

I keep .ui file together with python script.

Widget promotion is done this way:

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 and .ui files can be found here: https://gofile.io/?c=BUOjQE


Solution

  • I think I've asked too fast (before digging in PySide2 Docs):

    The solution is to add:

    loader.registerCustomWidget(MyCustomButton)
    

    in ExampleForm init method.