Search code examples
c++qtuser-interfaceqwidget

How to hide another class ui using Qt C++?


I've been trying to hide another class ui, but I can't figure it out.

As an example I have the MainWindow class and other two classes. This is a scheme of the MainWindow ui:

[---------------][---------------]

[ Class A ui ][ Class B ui ]

[---------------][---------------]

The top & bottom lines are just to outline the window. You can imagine it as a rectangle containing two rectangles with the classes ui inside.

When I click on a QPushButton in class A I want to hide class B ui.

This is a code snippet:

ClassA.h

#ifndef CLASSA_H
#define CLASSA_H

#include <QWidget>

namespace Ui {
class ClassA;
}

class ClassA : public QWidget
{
    Q_OBJECT

public:
    explicit ClassA(QWidget *parent = nullptr);
    ~ClassA();
    
public slots:
    void on_pushButton_clicked();
    
private:
    Ui::ClassA *ui;
};

#endif // CLASSA_H

ClassA.cpp
#include "classa.h"
#include "ui_classa.h"

ClassA::ClassA(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClassA)
{
    ui->setupUi(this);
}

ClassA::~ClassA()
{
    delete ui;
}

void classA::on_pushButton_clicked()
{
    // code to hide ClassB ui
}

ClassB & MainWindow are brand new (standard). ClassB ui contains some labels, pushButtons, ... . MainWindow ui contains two QWidgets that are promoted to ClassA ui & ClassB ui.

What code should I write in the on_pushButton_clicked() slot? I've made some tries but nothing seems to work.

Any help would be much appreciated.


Solution

  • one way is to add a signal in ClassA and emit it when clicking on the considered push button:

    #ifndef CLASSA_H
    #define CLASSA_H
    
    #include <QWidget>
    
    namespace Ui {
    class ClassA;
    }
    
    class ClassA : public QWidget
    {
        Q_OBJECT
    
    public:
        explicit ClassA(QWidget *parent = nullptr);
        ~ClassA();
        
    public signals:
        void notifyButtonClicked();
    
    public slots:
        void on_pushButton_clicked();
        
    private:
        Ui::ClassA *ui;
    };
    
    #endif // CLASSA_H
    

    and in classA.cpp we have:

    void classA::on_pushButton_clicked()
    {
        emit notifyButtonClicked();
    }
    

    now you can write this code in mainwindow constructor (assume _A is an object of ClassA):

    connect(_A, &ClassA::notifyButtonClicked, this, [] {
         // some code for hiding ClassB
    });
    

    I haven't tested this, because I dont have Qt on this machine, but that should work, with possible minor modifications. If any errors appear, let me know and I will help. Also, read the signals and slots documentation.