I have a Qt main window that will pop up a dialog box that has an OK and Cancel button. This dialog has a simple spinner that asks a user for a number that should be returned to the main window when OK or Cancel is pressed (for cancel, it will just send back -1).
I thought about using code in a signal in mainWindow.cpp like so:
void mainWindow::slot_openNumberDlg(){
// Create a new dialog
numberDlg dlg( this );
// Show it and wait for Ok or Cancel
if( dlg.exec() == QDialog::Accepted ){
return;
}
}
But how would I return the value of the spinner in the dialog back to main window if it is destroyed when the button is pressed?
I also thought about an alternative solution where I would initialize the dialog in mainWindow's constructor, but it isn't shown until a signal activated a slot in mainWindow.cpp like so:
// Create as pointer in main.h:
numberDlg *dlg;
// Initialize pointer and setup listener in constructor (main.cpp):
mainWindow::mainWindow(){
dlg = new numberDlg();
QObject::connect( dlg, SIGNAL( sig_retVal(int) ), ui->widget, SLOT( slot_showNum(int) ) );
}
// Make a function to handle show/close:
void mainWindow::slot_numberOpenClose(bool trigger){
if(trigger){
dlg->show();
} else {
dlg->close();
}
}
The above code would be able to send the number from the dialog's spinner to mainWindow using a signal/slot, but it won't lock out mainWindow. I do not want the user to continue using mainWindow until the dialog has been accepted or rejected.
Any ideas on how I can lock the main window and send a number back to main on dialog close?
What you should do is create a function in your dialog class that returns the value you want, and use it like so from your main window:
void mainWindow::slot_openNumberDlg(){
// Create a new dialog
numberDlg dlg( this );
// Show it and wait for Ok or Cancel
if( dlg.exec() == QDialog::Accepted ){
m_theValue = dlg.myValue(); // <--
return;
}
} // dlg goes out of scope
dlg won't be destroyed until it goes out of scope where I placed the comment, so your method will work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With