Change mainwindow ui label text using another class
Hi,
I have a problem, i created a mainwindow UI that has pushbutton and label "text" like in this picture https://prnt.sc/soz9tm
and Rain ui that has pushbutton like in this picture https://prnt.sc/sozbaq
When i compile program, first it opens mainwindow ui and when i clik on pushbutton it opens rain ui.
I want when i click on rain ui's pushbutton to set mainwindow's label text to "It rains",
but i don't know how to access mainwindow's label with Rain's class.
here are my codes and what i tried
mainwindow.h
Code:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "rain.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
{
Q_OBJECT
public:
MainWindow
(QWidget *parent
= nullptr
);
~MainWindow();
private slots:
void on_pushButton_clicked();
public:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
Code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow
::MainWindow(QWidget *parent
) , ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
this->hide();
rain *test = new rain();
test->show();
}
rain.h
Code:
#ifndef RAIN_H
#define RAIN_H
#include <QWidget>
#include "mainwindow.h"
namespace Ui {
class rain;
}
{
Q_OBJECT
public:
explicit rain
(QWidget *parent
= nullptr
);
~rain();
private slots:
void on_pushButton_clicked();
private:
Ui::rain *ui;
};
#endif // RAIN_H
rain.cpp
Code:
#include "rain.h"
#include "ui_rain.h"
#include "mainwindow.h"
ui(new Ui::rain)
{
ui->setupUi(this);
}
rain::~rain()
{
delete ui;
}
void rain::on_pushButton_clicked()
{
this->hide();
MainWindow *ma = new MainWindow(this);
ma->show();
}
Re: Change mainwindow ui label text using another class
Quote:
but i don't know how to access mainwindow's label with Rain's class.
You don't. Implement a signal for your rain class that gets emitted when the user clicks the button. In your MainWindow class, implement a slot to receive this signal. When you create your rain class in MainWindow:: on_pushbutton_clicked(), connect rain's signal to MainWindow's slot.
If you don't understand how to implement custom signals and slots, read the documentation.
Your code as written has a memory leak: Each time your clicked slot is executed, you create a new rain instance. This instance is never destroyed, so it is a memory leak. What you should do instead is make a "rain *" member variable in your MainWindow class, create the rain instance in the MainWindow constructor, and connect the signal and slot. In the clicked slot, simply call show() on this rain instance.
Re: Change mainwindow ui label text using another class
Took some time to learn signal and slot implementation, and i did everything as you said
Thank you, it works perfectly