Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

UI (Qt Designer) and inheritance



  • Hello,
    I'm trying to create a base window class, and then some derived windows with their own UI.
    Let's assume I have BaseWindow and DerivedWindow. Both were created with Qt Designer.
    BaseWindow has an action "test". DerivedWindow also has an action "test", and a checkbox.
    Sources files (probably useless for this question):

    BaseWindow.h

    namespace Ui {
    class BaseWindow;
    }
    
    class BaseWindow : public QMainWindow
    {
    
    public:
        explicit BaseWindow(QWidget *parent = nullptr) :
            QMainWindow(parent),
            ui(new Ui::BaseWindow)
        {
            ui->setupUi(this);
            connect(ui->actionTest, &QAction::triggered, this, [&]()
            {
                QTextStream(stdout) << "Test action triggered from base window";
            });
        }
        ~BaseWindow()
        {
            delete ui;
        }
    
    private:
        Ui::BaseWindow *ui;
    };
    

    DerivedWindow.h

    namespace Ui {
    class DerivedWindow;
    }
    
    class DerivedWindow : public BaseWindow
    {
    
    public:
        explicit DerivedWindow(QWidget *parent = nullptr) :
            BaseWindow (parent),
            ui(new Ui::DerivedWindow)
        {
            ui->setupUi(this);
    
            connect(ui->checkBox, &QCheckBox::clicked, this, [&](){
                QTextStream(stdout) << "Checkbox clicked in derived window";
            });
        }
    
        ~DerivedWindow()
        {
            delete ui;
        }
    
    private:
        Ui::DerivedWindow *ui;
    };
    

    If I click the "test" action in DerivedWindow, nothing will happen. This is expected, since I haven't connected it and both "test" actions are completely separate.

    My question is: is it possible to make an UI file inherit from another UI file? So that if I click the "test" action in DerivedWindow, it will work as if it had been clicked in BaseWindow, and print a message?

    Thanks.


  • Lifetime Qt Champion

    Hi,

    I may be wrong but I don't think you can do that in an automated way.

    What is you use case exactly ?



  • It will be better explained with screenshots.
    TES5 SSE FO4

    As you can see, those three windows are very similar, but they have some differences. So, making a common base would allow to remove duplicated code.


  • Moderators

    @G_ka said in UI (Qt Designer) and inheritance:

    those three windows are very similar, but they have some differences. So, making a common base would allow to remove duplicated code.

    Instead of creating 3 different window classes, consider using just one class. Dynamically show() or hide() the group boxes depending on which test you want to run.



  • @JKSH I was hoping for a better solution, but this looks like this solution is the easier one. Thanks.


Log in to reply