Customising code of Qt designer widget?

痴心易碎 提交于 2019-11-26 23:13:23

The most common way to solve this is by using widget promotion. This will allow you to replace a widget defined in Qt Designer with your own custom class. The steps for doing this are as follows:

In Qt Designer, select the QGraphicsView you want to replace, then right-click it and select Promote to... . In the dialog, set Promoted class name to "custom_gv", and set Header file to the python import path for the module that contains this class (e.g. "mypkg.widgets"). Then click Add, and Promote, and you will see the class change from "QGraphicsView" to "custom_gv" in the Object Inspector pane.

When the Qt Designer ui file is converted into PyQt code, it will automatically add an import statement like this:

from mypkg.widgets import custom_gv

and then in the converted code it will replace something like this:

    self.graphicsView = QtWidgets.QGraphicsView(MainWindow)

with this:

    self.graphicsView = custom_gv(MainWindow)

So the code in the ui file knows nothing about the custom class: it's just a name that is imported from elsewhere. That means you are completely free to write the custom class in any way you like.

In PyQt, this mechanism works in the same way with pyuic as it does with the uic module. The loadUi and loadUiType functions generate exactly the same code as pyuic does. The only difference is that the pyuic tool writes the generated code to a file, whereas the uic module loads it directly via exec.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!