2012-11-16 40 views

回答

88

QLineEdit::setValidator(),例如:

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

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

參見:QIntValidatorQDoubleValidatorQLineEdit::setValidator

+4

這可以從Qt Designer完成,還是隻有通過代碼才能實現? – sashoalm

+2

據我所知,設計師無法做到這一點。 – Chris

+0

如果您需要以科學記數法(例如,'3.14e-7')輸入,這是一個快速解決方案。 'QDoubleSpinBox'不接受科學記數法中的數字(Qt 5.5)。 –

16

最好是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))); 
+1

即使OP想要使用QLineEdit,使用QSpinBox絕對是最好的方法。 – DrHaze

+1

這適用於數字範圍很小的情況。想想你可能想要使用這個小部件的年齡或ID。 – Steve

+0

任何方式使旋轉盒更友好的鍵盤只能使用數字鍵,小數點分隔符和退格符? – Micka

7

您還可以設置一個inputMask

QLineEdit.setInputMask("9") 

這允許用戶鍵入只有一個數字,從09。使用多個9來允許用戶輸入多個號碼。另見完整的list of characters that can be used in an input mask

(我的答案是Python,但它不應該是很難將它轉換成C++)

5

你爲什麼不使用QSpinBox用於此目的?您可以設置使用以下行代碼的無形的上/下按鈕:

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

如果您在使用Qt Creator的5.6,你可以是這樣做的:

#include <QIntValidator> 

ui->myLineEditName->setValidator(new QIntValidator); 

我建議你把在ui-> setupUi(this)之後行;

我希望這會有所幫助。

+4

您的構造函數調用應該是'new QIntValidator(this)',否則只要您的小部件超出範圍,驗證器對象就會泄漏。 – Alexandros

相關問題