QDialogButtonBox 按钮没有响应

QDialogButtonBox buttons not responding

本文关键字:响应 按钮 QDialogButtonBox      更新时间:2023-10-16

当我运行以下函数时,对话框显示所有内容都已到位。问题是按钮无法连接。"确定"和"取消"不响应鼠标单击。

void MainWindow::initializeBOX(){
        QDialog dlg;
        QVBoxLayout la(&dlg);
        QLineEdit ed;
        la.addWidget(&ed);

        //QDialogButtonBox bb(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
        //btnbox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
         QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok |     QDialogButtonBox::Cancel);
         connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
         connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
         la.addWidget(buttonBox);
         dlg.setLayout(&la);

        if(dlg.exec() == QDialog::Accepted)
        {
            mTabWidget->setTabText(0, ed.text());
        }
      }

在运行时,cmd 中的错误显示:没有像 accept() 和 reject() 这样的插槽。

您在连接中指定了错误的接收器。它是具有accept()reject()插槽的对话框,而不是主窗口(即 this )。

因此,相反,您只需要:

 connect(buttonBox, SIGNAL(accepted()), &dlg, SLOT(accept()));
 connect(buttonBox, SIGNAL(rejected()), &dlg, SLOT(reject()));

现在,当您单击按钮时,对话框将关闭,exec()将返回QDialog::Accepted为"确定",或"QDialog::Rejected"表示"取消"。