Связь разных форм
Есть 2 формы, на MainWindow 2 кнопки. Одна вызывает новое окно. В новом окне тоже есть кнопка. Как при нажатии на кнопку во второй форме передать название этой кнопки во вторую кнопку на первой форме? Объяснение в скрине: ссылка
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "test.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tests = new test();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_2_clicked()
{
tests->show();
hide();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "test.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
test *tests;
};
#endif // MAINWINDOW_H
test.cpp
#include "test.h"
#include "ui_test.h"
test::test(QWidget *parent) :
QWidget(parent),
ui(new Ui::test)
{
ui->setupUi(this);
}
test::~test()
{
delete ui;
}
void test::on_pushButton_clicked()
{
close();
}
test.h
#ifndef TEST_H
#define TEST_H
#include <QWidget>
namespace Ui {
class test;
}
class test : public QWidget
{
Q_OBJECT
public:
explicit test(QWidget *parent = nullptr);
~test();
private slots:
void on_pushButton_clicked();
private:
Ui::test *ui;
};
#endif // TEST_H
Ответы (1 шт):
Автор решения: e.n.shirokov
→ Ссылка
Определи в классе окна сигнал и посылай его при нажатии кнопки:
test.h
class test : public QWidget
{
...
signals:
void sendTextFromButton(QString); // сигнал
private slots:
void on_pushButton_clicked();
...
};
test.cpp
void test::on_pushButton_clicked() {
emit sendTextFromButton(ui->mybutton->text()); // отправляем сигнал по нажатию кнопки
close();
}
Создай слот в главном окне, куда будет приходит сигнал:
mainwindow.h
class MainWindow : public QMainWindow
{
...
private slots:
void onSendTextFromButton(QString text);
...
};
Пропиши коннект сигнал-слот:
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tests = new test();
connect(tests, &test::sendTextFromButton, this, &MainWindow::onSendTextFromButton);
}
void MainWindow::onSendTextFromButton(QString text) {
ui->mybutton->setText(text);
}
Так же можно почитать про сигналы и слоты