首页 文章

将QLineEdit设置为仅接受数字

提问于
浏览
65

我有 QLineEdit ,用户应该只输入数字 .

QLineEdit 是否只有数字设置?

5 回答

  • 20

    QLineEdit::setValidator() ,例如:

    myLineEdit->setValidator( new QIntValidator(0, 100, this) );
    

    要么

    myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );
    

    见:QIntValidatorQDoubleValidatorQLineEdit::setValidator

  • 7

    最好的是QSpinBox .

    并且对于双值使用QDoubleSpinBox .

    QSpinBox myInt;
    myInt.setMinimum(-5);
    myInt.setMaximum(5);
    myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
    myInt.setValue(2);// Default/begining value
    myInt.value();// Get the current value
    //connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));
    
  • 5

    你也可以设置inputMask

    QLineEdit.setInputMask("9")
    

    这允许用户只键入一个从 09 的数字 . 使用多个 9 来允许用户输入多个数字 . 另见完整list of characters that can be used in an input mask .

    (我的答案是在Python中,但将其转换为C并不难)

  • 0

    你为什么不为此目的使用 QSpinBox ?您可以使用以下代码行设置不可见的向上/向下按钮:

    // ...
    QSpinBox* spinBox = new QSpinBox( this );
    spinBox->setButtonSymbols( QAbstractSpinBox::NoButtons ); // After this it looks just like a QLineEdit.
    //...
    
  • 103

    如果你正在使用QT Creator 5.6,你可以这样做:

    #include <QIntValidator>
    
    ui->myLineEditName->setValidator( new QIntValidator);
    

    我建议你把这行放在ui-> setupUi(this)之后;

    我希望这有帮助 .

相关问题