is it possible to restrict the length in a QInputDialog::getText
? For example, I want to restrict the length from the user input to 10 characters directly in the InputDialog. Unfortunately, there isn't a function like QInputDialog::setMaximum
.
Here's my current code:
QString input = QInputDialog::getText(this, tr("Find"), tr("Enter text:"), QLineEdit::Normal, "", nullptr, Qt::WindowFlags(), Qt::ImhDialableCharactersOnly);
if (input == "")
return;
else if (input.length() > 10)
{
QMessageBox::warning(this, tr("Invalid input", "Note #1"), tr("Input is too long."));
// This is this function name (calls itself again)
on_actionFind_triggered();
}
...
Very easy with a signal/slot mechanism and a signal blocker...
#include <QApplication>
#include <QInputDialog>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QInputDialog w;
QObject::connect(&w, &QInputDialog::textValueChanged,
[&w](QString text){ if (text.length() > 10) { QSignalBlocker s(w); w.setTextValue(text.left(10)); } });
w.show();
return a.exec();
}
Another posibility would be to find QLineEdit
child of the dialog using and then assign a certain QValidator
to it. I have not tested this but it should work as well. But then you would need to program the maximum length validator.
auto lineEdit = inputDialog->findChild<QLineEdit*>();
lineEdit->setValidator(validator);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.