从qt中继承表单的最佳方式

The best way to inherit from form in qt

本文关键字:最佳 方式 表单 继承 qt      更新时间:2023-10-16

从qt设计器中创建的形式继承最可取的方式是什么?

没有直接继承form本身的好方法,你最好继承为form创建的类

class testBase : public QWidget
{
    Q_OBJECT
public:
    testBase (QWidget *parent = 0);
    ~testBase ();
protected: // here was private
    Ui::testBaseClass baseUi; // rename this
};
testBase ::testBase (QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
}

也,如果你想添加一些其他形式,这也是可能的,你应该做一些额外的工作:

1)在基类(某些容器)中为子ui指定一个占位符

2)使用向导创建子表单。不要把你的基类作为祖先传递,在向导中你应该说你继承自QWidget。

3)在为你的派生类创建表单之后,重写派生类,使其成为基类的后代。更改其构造函数,ui.setupUi(this)行应更改为ui.setupUi(baseUi.placeholder)

class testDerived : public testBase 
{
    Q_OBJECT
public:
    testDerived (QWidget *parent = 0);
    ~testDerived ();
private:
    Ui::testDerivedClass ui;
};
testDerived::testDerived(QWidget *parent)
    : testBase (parent)
{
    ui.setupUi(baseUi.placeholder);
}

还要注意,派生类不改变基类的形式,它扩展基类。您将无法在表单构造函数中向基表单添加或删除项,但是您指定为占位符的容器将被派生类的表单数据填充。