Search code examples
c++qtinheritanceqpushbutton

C++ Qt inherit from custom widget


I'm working on a project with Qt and C++. Now my Question is:

Is inheritance possible in UI classes?

For example: This is the Widget I want to inherit from

//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

//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?

I can add a QPushButton but the text set in WindowA would also be set in WindowB. The problem is to set a different text for the button in WindowB than it is set for the button in WindowA


Solution

  • 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!");
    }