如何将信号从MainWindow连接到Dialog中的Slot

时间:2017-04-13 23:07:57

标签: c++ qt

我的MainWindow中有信号发出一个行编辑中的数字。当我单击按钮打开对话框时,我希望将该数字复制到对话框中的行编辑中。我无法连接它。我可以看到信号是用qDebug发出的。我连错了还是错了?我尝试了很多方法。这是我的代码片段。

主窗口

//My MainWindow
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {

    ui->setupUi(this);

    //This is the number I am trying to send to the dialog
    ui->checkingAmount->setText(QString::number(1000.00, 'f', 2));
    ui->checkingAmount->setReadOnly(true);     
}

//Emit the data here
void MainWindow::on_transferButton_clicked() {

 transferWindow = new TransferWindow(this);
 transferWindow->show();

 //trying to emit the data
 QString data =ui->checkingAmount->text();
 emit shareCheckingData(data);             
 qDebug()<<"emitting mainwin amount";

}

对话框

//My Dialog
TransferWindow::TransferWindow(QWidget *parent) : QDialog(parent),ui(new Ui::TransferWindow) {

    ui->setupUi(this); 

    //I have tried several variations of this
    //mainWindow = new MainWindow();
    connect(mainWindow, SIGNAL(shareCheckingData(QString)),this, SLOT(getAmountFromMainWin(QString)));
}

//Here is the connecting slot to get the data from main window
void TransferWindow::getAmountFromMainWin(QString n) {

    float CheckTotal = n.toFloat();
    ui->checkingAmount->setReadOnly(true);
    ui->checkingAmount->setText(QString::number(CheckTotal));
    qDebug()<<"setting amount";
}

如何才能连接?我阅读了很多帖子,并没有解决问题。感谢。

1 个答案:

答案 0 :(得分:0)

我在你的代码的注释中注意到你打算创建一个MainWindow的实例并尝试连接到这个实例,这是一个与前一个实例不同的新实例,所以你将无法获得它

首先,我们必须创建实例,然后连接它,我们可以在构造函数中完成。

<强> MainWindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->checkingAmount->setText(QString::number(1000.00, 'f', 2));
    ui->checkingAmount->setReadOnly(true);

    transferWindow = new TransferWindow(this);

    connect(this, &MainWindow::shareCheckingData, transferWindow, &TransferWindow::getAmountFromMainWin);
    //old style
    //connect(this, SIGNAL(shareCheckingData(QString)), transferWindow, SLOT(getAmountFromMainWin(QString)));
}

void MainWindow::on_transferButton_clicked()
{

    //trying to emit the data
    QString data =ui->checkingAmount->text();
    emit shareCheckingData(data);
    qDebug()<<"emitting mainwin amount";

    transferWindow->show();

}

<强> TransferWindow.cpp

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

void TransferWindow::getAmountFromMainWin(QString n)
{
    float CheckTotal = n.toFloat();
    ui->checkingAmount->setReadOnly(true);
    ui->checkingAmount->setText(QString::number(CheckTotal));
    qDebug()<<"setting amount";
}