Reputation: 5659
I have a simple code; here I've two buttons, I press the first one and it shows a MsgBox. Then I press the "Okay", and it should call a connected action written in a second button, but it doesn't. Instead I get an error:
Object::connect: No such signal QMessageBox::buttonClicked(QMessageBox::Ok)
Object::connect: (receiver name: 'OpenFile_Bttn')
The code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_OpenFile_Bttn_clicked(){
QFileDialog::getOpenFileName(this,tr("Open file"), "", tr(""));//Open a dialog "OpenFile"
}
void MainWindow::on_pushButton_clicked(){
QMessageBox msgBox;
msgBox.setText("Push button to choose a file");
//Connect clicking button in MsgBox to an action in OpenFile_Bttn button
QWidget::connect(&msgBox,SIGNAL(buttonClicked(QMessageBox::Ok)),
ui->OpenFile_Bttn, SLOT(on_OpenFile_Bttn_clicked()));
msgBox.exec();//Show MsgBox
}
Also I found an interesting thing, that the error message appears when a MsgBox popup, but not when I click the button "Ok" inside the MsgBox.
Upvotes: 2
Views: 1488
Reputation: 4607
If you do this instead you get a compiler error, that way you can see something is wrong at compile instead of runtime error
QObject::connect(msgBox, &QMessageBox::buttonClicked, ui->OpenFile_Bttn, &QPushButton::clicked);
out of interest the above code is untested and probably wont compile but basicallt just do sender, signal, reciever, slot but use their class object to select signal and slots like shown above and then you will get an easier to spot compile error that tells you what could be wrong
Upvotes: 2
Reputation: 4029
No need for signals here, exec returns the button clicked.
void MainWindow::on_OpenFile_Bttn_clicked(){
QFileDialog::getOpenFileName(this,tr("Open file"), "", tr(""));//Open a dialog "OpenFile"
}
void MainWindow::on_pushButton_clicked(){
QMessageBox msgBox;
msgBox.setText("Push button to choose a file");
//Connect clicking button in MsgBox to an action in OpenFile_Bttn button
if(msgBox.exec() == QMessageBox::Ok)
{
on_OpenFile_Bttn_clicked();
}
}
If you want to use custom buttons you can still call msgBox.buttonClicked()
after exec to find out which button was clicked.
Upvotes: 5