可以使用QRegExpValidator类来限制QLineEdit只能输入数字。以下是示例代码:
#include <QApplication>
#include <QLineEdit>
#include <QRegExp>
#include <QRegExpValidator>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QLineEdit lineEdit;
QRegExp regExp("[0-9]*"); // 只允许输入数字
lineEdit.setValidator(new QRegExpValidator(regExp));
lineEdit.show();
return a.exec();
}
在上面的示例中,我们使用QRegExp类创建了一个正则表达式,其中[0-9]表示只匹配数字字符,*表示可以重复零次或多次。然后,我们将该正则表达式传递给QRegExpValidator构造函数,并将其设置为QLineEdit的验证器。这样,只有数字才能在QLineEdit中输入。