QUiLoader: requirements for loading .ui file with custom widgets?

家住魔仙堡 提交于 2019-12-02 01:23:57

You need to create your own derived version of QUiLoader, and provide an implementation of the factory method QUiLoader::createWidget that can create your widgets.

You could factor this out into a plugin that gets loaded by the QUiLoader. It would have to implement a QDesignerCustomWidgetInterface instance. See the Custom Widget Plugin Example for a complete example of a plugin.

// https://github.com/KubaO/stackoverflown/tree/master/questions/uiloader-custom-37775472
#include <QtUiTools>
#include <QtWidgets>

const char uiData[] =
    "<ui version=\"4.0\"><class>Widget</class><widget class=\"MyWidget\" name=\"Widget\">\n"
        "<property name=\"windowTitle\" ><string>Widget</string></property>\n"
        "</widget><pixmapfunction></pixmapfunction><resources/><connections/>\n"
    "</ui>";

class MyWidget : public QLabel
{
    Q_OBJECT
    bool m_closed = false;
public:
    MyWidget(QWidget* parent = 0) : QLabel("This is MyWidget", parent) {}
    bool isClosed() const { return m_closed; }
    void closeEvent(QCloseEvent *) Q_DECL_OVERRIDE { m_closed = true; }
};

class MyUiLoader : public QUiLoader {
public:
    MyUiLoader(QObject * parent = 0) : QUiLoader(parent) {}
    QWidget * createWidget(const QString & className, QWidget * parent = 0,
                           const QString & name = QString()) {
        if (className == "MyWidget") {
            MyWidget * w = new MyWidget(parent);
            w->setObjectName(name);
            return w;
        }
        return QUiLoader::createWidget(className, parent, name);
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QBuffer buf;
    buf.setData(uiData, sizeof(uiData));
    MyUiLoader uiLoader;
    auto uiMain = qobject_cast<MyWidget*>(uiLoader.load(&buf));
    uiMain->show();
    return app.exec();
}

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