简体   繁体   中英

How to restrict the content of QInputDialog::getText

I want to input Hex number with QInputDialog , and there is only getInt , getDouble , getItem and getString . Only the getSring can take in char like "a,b,c,d,e,f". However, is there someway to restrict getString only take 0~9||"af"

QSpinBox are widgets oriented to obtain numbers from the client input, this has the method setDisplayIntegerBase() that indicates in which numerical base it is desired to use, in this case it is necessary to use base 16.

So if you look at the method getInt() has an internal QSpinBox then only that property should be enabled, there is no direct method to get the QSpinBox , but we can use the findchild() method.

#include <QInputDialog>
#include <QSpinBox>

static QString getHex(QWidget *parent,
                      const QString &title,
                      const QString &label,
                      int value = 0,
                      int min = -2147483647,
                      int max = 2147483647,
                      int step = 1,
                      bool *ok = Q_NULLPTR,
                      Qt::WindowFlags flags = Qt::WindowFlags()){
    QInputDialog dialog(parent, flags);
    dialog.setWindowTitle(title);
    dialog.setLabelText(label);
    dialog.setIntRange(min, max);
    dialog.setIntValue(value);
    dialog.setIntStep(step);
    QSpinBox *spinbox = dialog.findChild<QSpinBox*>();
    spinbox->setDisplayIntegerBase(16);

    bool ret = dialog.exec() == QDialog::Accepted;
    if (ok)
        *ok = ret;
    return spinbox->text();
}

Example:

#include <QApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qDebug()<<getHex(Q_NULLPTR, "title", "label", 0x1d, 0);
    return 0;
}

Screenshot:

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM