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||"a-f"
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: