将参数从QtMessageBox信号传递到buttonClick信号处理程序槽

Passing parameters from QtMessageBox signals to buttonClick signal Handler slot

本文关键字:buttonClick 信号处理 程序 参数 QtMessageBox 信号      更新时间:2023-10-16

我试图创建一个弹出窗口,将(1)是非模态的,(2)承载上下文数据,将在以后处理时,用户单击ok事件。到目前为止,我有下面的代码确实弹出作为一个非模态。我知道msgBox->open(this, SLOT(msgBoxClosed(QAbstractButton *))msgBoxClosed(QAbstractButton *button)工作,但当我将QStringList collisionSections添加到SLOT参数时。我得到这个错误:

QObject::connect: No such slot MainWindow::msgBoxClosed(QAbstractButton *, collisionSections) in srcmainwindow.cpp:272
QObject::connect:  (receiver name: 'MainWindow')

我理解,因为它在那里声明槽,但我不知道如何去做我想做的事情,这是在QString作为内容传递给我的信号,并让它与qmessagebox在OK单击上抛出的buttonClicked()事件很好地发挥作用。我也可能是接近这个错误的方式,请让我知道如果是这样。任何帮助都非常感激!

void MainWindow::do_showCollisionEvt(QStringList collisionSections)
{
    QString info = "Resolve sections";
    for (QString section : collisionSections)
    {
        if (!section.isEmpty())
        {
            info.append(" [" + section + "] ");
            qDebug() << "Emitting node off for:" << section;
            emit nodeOff(section);
        }
    }
    QMessageBox *msgBox = new QMessageBox;
    msgBox->setAttribute(Qt::WA_DeleteOnClose);
    msgBox->setText("Collision event detected!");
    msgBox->setInformativeText(info);
    msgBox->setStandardButtons(QMessageBox::Ok);
    msgBox->setDefaultButton(QMessageBox::Ok);
    msgBox->setModal(false);
    msgBox->open(this, SLOT(msgBoxClosed(QAbstractButton *, collisionSections)));
}

void MainWindow::msgBoxClosed(QAbstractButton *button, QStringList collisionSections) {
    QMessageBox *msgBox = (QMessageBox *)sender();
    QMessageBox::StandardButton btn = msgBox->standardButton(button);
    if (btn == QMessageBox::Ok)
    {
        for (QString section : collisionSections)
        {
            if (!section.isEmpty())
            {
                qDebug() << "Emitting nodeON for:" << section;
                emit nodeOn(section);
            }
        }
    }
    else
    {
        throw "unknown button";
    }
}

首先,open()将您的插槽连接到finished()信号,没有参数,或者如果第一个插槽参数是指针(您的情况),则连接到buttonClicked()信号。

。您没有正确地传递参数。您不能在声明期间这样做,slot接收的参数是在信号发射中设置的,在您的情况下,您无法控制。在SLOT中,你只能声明参数TYPES而不是它们的值(注意SLOT只是一个宏,实际上SLOT(…)的结果只是一个字符串(char*))。

我建议你对消息框使用setProperty()方法,例如:

msgBox->setModal(false);
msgBox->setProperty("collisionSections", collisionSections);
msgBox->open(this, SLOT(msgBoxClosed(QAbstractButton *)));

你的位置可以是这样的:

void MainWindow::msgBoxClosed(QAbstractButton *button) {
    QMessageBox *msgBox = (QMessageBox *)sender();
    QStringList collisionSections = msgBox->property("collisionSections").toStringList();