我想传递变量的值,换句话说,我想在MainWindow中初始化Dialog类的变量并执行Dialog窗口。我可以使用构造函数成功初始化Dialog类的变量。但是当我尝试使用Dialog类中定义的公共函数初始化私有或公共变量时,它不起作用。请参阅以下代码:
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(const QString &d, QWidget *parent = 0);
~Dialog();
void setDat(const QString &k);
private:
Ui::Dialog *ui;
QString msg;
QString msg2;
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(const QString &d, QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
msg = d;
ui->label->setText(msg);
ui->label_2->setText(msg2);
}
void Dialog::setDat(const QString &k)
{
msg2 = k;
}
Dialog::~Dialog()
{
delete ui;
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString temp = "Hello....";
Dialog dg(temp);
dg.setDat(temp);
dg.exec();
}