1.使用QT project创建一个QT custom designer widget
image.png

2.创建后得到的文件目录如图所示
image.png

components.cpp 主要是进行组件合并,将cpushbutton和ctoolbutton合并,再增加组件也是类似写法
image.png

3.构建release版本,将生成的.dll文件拷贝到qt creator里的designer的plugin里
image.png

4.在qt designer的设计师里可以直接拖动生成的组件使用

问题:
1.为啥我按步骤走后,qt creator的设计师里没有该组件?
请确保你的组件构建版本与qt creator版本一致
image.png
image.png

2.定义了一个组件,想自定义头文件的引用,却发现它一直是小写?尝试过在QDesignerCustomWidgetInterface里实现includeFile,还是不行?
请重写domxml方式,在里面添加header

QString CWidgetPlugin::domXml() const
{
    return QLatin1String(R"(
    <ui language="c++">>
      <widget class="CWidget" name="cWidget"/>
    )"
    R"(
        <customwidgets>
          <customwidget>
            <header>CWidget.h</header>
          </customwidget>
        </customwidgets>
    ")
    R"(
    </ui>
    )");
}

3.定义了一个容器组件,继承自QWidget,为啥样式不生效?
请重写paintEvent方法

void CWidget::paintEvent(QPaintEvent *event)
{
    QStyleOption styleOpt;
    styleOpt.initFrom (this);
    QPainter painter(this);
    style()->drawPrimitive (QStyle::PE_Widget,&styleOpt,&painter,this);
    QWidget::paintEvent(event);
}

或者在它的构造函数里添加 this->setAttribute( Qt::WA_StyledBackground);

4.定义了一个容器组件,继承自QWidget,为啥在qt designer里不能拖拉子组件进去?尝试过在QDesignerCustomWidgetInterface里实现isContainer方法,return true,还是不行?
请重写domxml方法,在里面添加container

QString CWidgetPlugin::domXml() const
{
    return QLatin1String(R"(
    <ui language="c++">>
      <widget class="CWidget" name="cWidget"/>
    )"
    R"(
        <customwidgets>
          <customwidget>
            <container>1</container>
          </customwidget>
        </customwidgets>
    ")
    R"(
    </ui>
    )");
}

5.为啥我的类继承了QPushButton(其他同理),在*.ui描述文件里是QWidget?
请重写domxml方法,在里面添加extends

QString CPushButtonPlugin::domXml() const
{
    return QLatin1String(R"(
    <ui language="c++">>
      <widget class="CPushButton" name="cPushButton"/>
    )"
    R"(
        <customwidgets>
          <customwidget>
            <extends>QPushButton</extends>
          </customwidget>
        </customwidgets>
    ")
    R"(
    </ui>
    )");
}

点墨
26 声望3 粉丝

全栈前端开发工程师