I have a simple Qt6 project created in Qt Creator. This is a window with just one button. I want this button to disappear and a text (in a QLabel) to appear when the button is clicked.
#include "mainwindow.h"
#include "./ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(ui->pushButton, &QPushButton::pressed, this, &MainWindow::generate);
}
void MainWindow::generate() {
delete ui->pushButton;
QLabel* a = new QLabel("Text", ui->centralwidget);
}
MainWindow::~MainWindow()
{
delete ui;
}
When I press the button, it disappears, but the text doesn't appear.
When I move:
QLabel* a = new QLabel("Text", ui->centralwidget);
to the constructor, after ui->setupUi(this);
line, the text appears.
Why doesn't it appear after pressing the button? How to fix it?
Abstract Qt example:
#include <QApplication>
#include <QMainWindow>
#include <QWidget>
#include <QPushButton>
class Window : public QMainWindow {
Q_OBJECT
public:
explicit Window(QWidget* p = nullptr) : QMainWindow(p) {
btn_ = new QPushButton(this);
// ...
// If button pressed we call foo();
connect(btn_, &QPushButton::pressed, this, &Window::foo);
}
void foo() {
w_ = new QWidget(this);
// ...
btn_->hide();
w_->show(); // !
}
private:
QPushButton* btn_{};
QWidget* w_{};
}
We create the button. We want to create a new widget when button is pressed. So we just create widget, then set its parameters(like position, styles, etc.), and finally we call show()
to show widget(there is also hide()
to hide widget).
We need to storage widgets in dynamic memory, because in other way variable will die, when function end.
Personal recommendation:
In this example I have two private fields of class to store widgets. But in big programs we need a lot of widgets. So just store it in std::map<std::string, QWidget*> objects
, so you can control memory more effectively and has understandable access to widgets.