【问题标题】:How to set maximum length for QInputDialog Text如何设置 QInputDialog 文本的最大长度
【发布时间】:2021-10-21 14:47:44
【问题描述】:

是否可以限制QInputDialog::getText 的长度?例如,我想直接在 InputDialog 中将用户输入的长度限制为 10 个字符。不幸的是,没有像QInputDialog::setMaximum 这样的函数。

这是我当前的代码:

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();
    }
...

【问题讨论】:

  • QInputDialog 没有那个功能;不过,您可能会继承并实现您想要的功能。

标签: c++ qt qt5 qinputdialog


【解决方案1】:

使用信号/插槽机制和信号拦截器非常容易......

#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();
}

另一种可能性是使用对话框找到QLineEdit 的子级,然后为其分配一个特定的QValidator。我没有对此进行测试,但它也应该可以工作。但是你需要编写最大长度验证器。

auto lineEdit = inputDialog->findChild<QLineEdit*>();
lineEdit->setValidator(validator);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多