Search code examples
c++qtqpushbuttonqdialog

How to close a dialog with an OK button using a condition


My dialog window

My code

my first attempt so I could get the result in Mainwindow.cpp but it could be //incorrect

void Dialog::on_buttonBox_accepted()
 {
     Cities.clear();
     for(int row = 0; row<ui->tableWidget->rowCount(); row++)
     {
         cities s(get_city(row),get_time(row,3),get_time(row,4));
         Cities.push_back(s);
     }
 }
// my attempt to make another button but I could not get a result in 
//Mainwindow.cpp but could check correctly
void Dialog::on_pushButton_clicked()
{
    if(cities_is_filled())
    {
        Cities.clear();
        for(int row = 0; row<ui->tableWidget->rowCount(); row++)
        {
            cities s(get_city(row),get_time(row,3),get_time(row,4));
            Cities.push_back(s);
        }
    }
}

//GET RESULT
void MainWindow::on_actionAdd_train_triggered()
{
    Dialog e;
    if(e.exec())
    {
       for(auto City: e.Cities)
       {
           ui->textBrowser->append(City.city_+ " " + City.depart_+ " " 
           +City.leave_);
       }
    }
}

If the table cell is empty when I press OK, the dialog closes - but I would like it to not close. How can I implement this?


Solution

  • Press right click mouse on your buttonBox then select Go To Slot... then choose accepted() slot.

    enter image description here

    enter image description here

    Now add your condition to the accepted function:

    void MainWindow::on_buttonBox_accepted()
    {
        if(ui->tableWidget->item(1,2)->text() != "") // for example
        {
    
        }
        else
        {
            qApp->exit();
        }
    }
    

    QDialogButtonBox Class