因此,如果您想完全控制它,您将需要制作自己的QDialog
,QLabel
为文本添加 a ,然后添加一行编辑,设置 a QValidator
,然后访问返回值。
像这样:
mydialog.h
#include <QDialog>
#include <QLineEdit>
class MyDialog : public QDialog
{
Q_OBJECT
public:
MyDialog(QWidget *parent = 0);
~MyDialog();
QString getNewValue();
signals:
//void rejected();
//void accepted();
public slots:
private:
QLineEdit * le;
};
mydialog.cpp
#include "mydialog.h"
#include <QDialogButtonBox>
#include <QRegExpValidator>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QLabel>
MyDialog::MyDialog(QWidget *parent)
: QDialog(parent)
{
le = 0;
this->setAttribute(Qt::WA_QuitOnClose, false);
QVBoxLayout * vbox = new QVBoxLayout;
vbox->addWidget(new QLabel(tr("Type in your text:")));
le = new QLineEdit();
// le->setText(tr("Profile"));
// le->selectAll();
le->setPlaceholderText(tr("Profile"));
vbox->addWidget(le);
QRegExpValidator * v = new QRegExpValidator(QRegExp("[\\w\\d_ \\.]{24}"));
le->setValidator(v);
QDialogButtonBox * buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok
| QDialogButtonBox::Cancel);
vbox->addWidget(buttonBox);
this->setLayout(vbox);
// connect(buttonBox, SIGNAL(accepted()), this, SIGNAL(accepted()));
// connect(buttonBox, SIGNAL(rejected()), this, SIGNAL(rejected()));
}
MyDialog::~MyDialog()
{
}
QString MyDialog::getNewValue()
{
return le->text();
}
示例用法:
MyDialog dialog;
if(dialog.exec() == QDialog::Accepted)
{
QString retVal = dialog.getNewValue();
qDebug() << "Dialog value:" << retVal;
}
实现几乎相同目的的另一种方法:
http://qt-project.org/doc/qt-4.8/qlineedit.html#inputMask-prop
http://qt-project.org/doc/qt-4.8/widgets-lineedits.html
如果您想使用股票getText
QInputDialog
,您可以设置以下字段InputMethodHint
:
http://qt-project.org/doc/qt-4.8/qinputdialog.html#getText
http://qt-project.org/doc/qt-4.8/qt.html#InputMethodHint-enum
但QRegExp
在我看来是最强大的。
QRegExp
下面是这个类的一些很好的例子:
http://qt-project.org/doc/qt-4.8/richtext-syntaxhighlighter-highlighter-cpp.html
classFormat.setFontWeight(QFont::Bold);
classFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
rule.format = classFormat;
highlightingRules.append(rule);
singleLineCommentFormat.setForeground(Qt::red);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
multiLineCommentFormat.setForeground(Qt::red);
quotationFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("\".*\"");
rule.format = quotationFormat;
highlightingRules.append(rule);
functionFormat.setFontItalic(true);
functionFormat.setForeground(Qt::blue);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rule.format = functionFormat;
highlightingRules.append(rule);
commentStartExpression = QRegExp("/\\*");
commentEndExpression = QRegExp("\\*/");
希望有帮助。