PDA

View Full Version : MessageBox comes before MainWindow



fakandere
2nd July 2012, 22:00
Hi all, I just started qt, so I don't have enough knowledge.


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

connectDatabase();
}

void MainWindow::connectDatabase()
{
QFile databaseFile("database.db");
if (!databaseFile.exists()) {
connectionError();
} else
{
db.setHostName("localhost");
db.setDatabaseName("database.db");
if (!db.open()) {
connectionError();
}
}
}

void MainWindow::connectionError()
{
QMessageBox msgBox;
msgBox.addButton(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setWindowTitle("Connection Error");
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Program cannot connect the database file which is required to run this software. Would you like to download default database file? Please note that all of the saved process data will be removed.");
int selection = msgBox.exec();

if (selection == QMessageBox::Yes) {
//restore data
} else {
MainWindow::close();
}

}


This is what I did. When I delete the database file to see connectionError function, messagebox comes before the MainWindow and MainWindow::close() doesnt work. What should I do?

jboban
2nd July 2012, 23:14
Instead of direct call connectDatabase(), make it slot, and than emit the signal:

emit doConnectDatabase();

fakandere
2nd July 2012, 23:47
Thanks for the reply,

I made it public slot and also changed its name to "doConnectDatabase"
and then, I typed

emit doConnectDatabase()
instead of

connectDatabase()

but nothing changed, any other ideas?

ChrisW67
3rd July 2012, 03:22
Your main window doesn't show because it is not even constructed at the time you fail to open the database. Your attempt to close the un-constructed window may schedule a close event but it will almost certainly be followed nearly immediately with the show event scheduled in your main().

You need to schedule the attempt to open the database for a point in time after the main window is constructed and visible. You can do this with a zero length, single shot timer. Convert you existing connectDatabase() to a slot and make your constructor look like this:


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

QTimer::singleShot(0, this, SLOT(connectDatabase()));
}


The window will finish construction, return to the main event loop and be shown before the timer fires. When the timer event is processed the connection error should function as you expect.