简体   繁体   English

C++ Qt 继承自自定义小部件

[英]C++ Qt inherit from custom widget

I'm working on a project with Qt and C++.我正在使用 Qt 和 C++ 开发一个项目。 Now my Question is:现在我的问题是:

Is inheritance possible in UI classes?在 UI 类中可以继承吗?

For example: This is the Widget I want to inherit from例如:这是我要继承的 Widget

//windowA.h
namespace Ui {
    class WindowA;
}

class WindowA : public QWidget
{
    Q_OBJECT

public:
    explicit WindowA(QWidget *parent = nullptr);
    ~AddWindow();

    QPushButton *button; 
};

//windowA.cpp
WindowA::WindowA(QWidget *parent) :
    QWidget(parent)
{
    button = new QPushButton();
    button->setText("Save");
    connect(button, SIGNAL (clicked()), this, SLOT (//slot));

    QGridLayout *layout = new QGridLayout();

    layout->addWidget(button, 0, 0);

    this->setLayout(layout);
}

This is the widget that inherits from WindowA这是继承自WindowA的小部件

//windowB.h
namespace Ui {
    class WindowB;
}

class WindowB : public WindowA
{
    Q_OBJECT

public:
    explicit WindowB(QWidget *parent = nullptr);
    ~WindowB();
};

How would I implement a QPushButton, so that it's possible to set different text in both classes?我将如何实现 QPushButton,以便可以在两个类中设置不同的文本?

I can add a QPushButton but the text set in WindowA would also be set in WindowB .我可以添加一个QPushButton,但在文本设置WindowA也将在设置WindowB The problem is to set a different text for the button in WindowB than it is set for the button in WindowA问题是设置在按钮不同的文字WindowB比它被设置在按钮WindowA

If I understand your question correctly, all you need to do is change what text you set on the button in your constructor:如果我正确理解您的问题,您需要做的就是更改您在构造函数中的按钮上设置的文本:

WindowB::WindowB(QWidget *parent) :
    WindowA(parent)
{
    button->setText("Something else!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM