PDA

View Full Version : Validate Data in QDialog



jcraig
13th July 2007, 21:48
Here's an easy one...I'm running Qt 4.3 on Red Hat. My dialog contains a QTextEdit. When the user presses OK, I need to make sure that the data in the QTextEdit is valid. Since I used Qt Designer to make the dialog, it has a QDialogButtonBox. I have connected the "clicked" signal to a slot which checks the size of the QTextEdit. If the size is adequate, I call "accept()" otherwise the slot just returns. The problem is that the dialog disappears even when accept() is not called. If I use the reject() function, the dialog still disappears.

Below is some code...thanks for any help or ideas.
Joel



DataSourceDlg :: DataSourceDlg()
{
connect(buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(checkValues(QAbstractButton*)));
}

void DataSourceDlg :: checkValues(QAbstractButton* button)
{

if (button->text() == "Cancel")
{
accept(); // dismiss dialog with user click on Cancel
} else {
if (nodeLineEdit->text() > 3) {
accept(); // dismiss dialog with valid data
}
}
return; // invalid data do not dismiss dialog
}

marcel
14th July 2007, 19:40
Probably because the "OK" button is the default dialog button, therefore is connected by default to the accept() slot.

The solution is to delete the default button box(with OK and Cancel) created by designer and to create your own.

Regards

jpn
15th July 2007, 13:00
How about a slot that validates contents of the dialog and enables/disables the button correspondingly? This slot would be connected to various content change signals of entry widgets in the dialog. It is usually a good idea to prevent insensible user actions.

jcraig
23rd July 2007, 16:49
I contacted Trolltech support. In case anyone searches this thread for a similar problem, I thought I'd send the resolution. It is not necessary to create one's own ok/cancel buttons, although that would probably work (I didn't try that). It is also not necessary to enable/disable the ok/cancel buttons, but that is a good idea (I didn't try that either). A simpler solution is to override the done() method and do the validation there. To make the dialog disappear, just call the parent's done() method. To keep the dialog on the screen, simply return. Here's some code...

Thanks for the ideas,
Joel :)



void DataSourceDlg::done(int r)
{
if(QDialog::Accepted == r) // ok was pressed
{
if(nodeLineEdit->text().size() > 3) // validate the data somehow
{
QDialog::done(r);
return;
}
else
{
statusBar->setText("Invalid data in text edit...try again...");
return;
}
}
else // cancel, close or exc was pressed
{
QDialog::done(r);
return;
}
}