日志
5.1 自定义Qt窗口部件
2015-11-27 21:48
//HexSpinBox.cpp
#ifndef HEXSPINBOX_H #define HEXSPINBOX_H #include <QSpinBox> class HexSpinBox : public QSpinBox { Q_OBJECT public: explicit HexSpinBox(QWidget *parent = 0); protected: QValidator::State validate(QString &input, int &pos) const; int valueFromText(const QString &text) const; QString textFromValue(int val) const; signals: public slots: private: QRegExpValidator *m_pValidator; }; #endif // HEXSPINBOX_H //HexSpinBox.cpp #include <QtGui> #include "HexSpinBox.h" HexSpinBox::HexSpinBox(QWidget *parent) : QSpinBox(parent), m_pValidator(new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"), this)) { setRange(0, 255); } //返回输入值是否有效 //Invalid 无效 //Intermediate 部分有效 //Acceptable 有效 QValidator::State HexSpinBox::validate(QString &input, int &pos) const { return m_pValidator->validate(input, pos); } //字符串转为数值 //在输入框输入时被调用 int HexSpinBox::valueFromText(const QString &text) const { bool ok; return text.toInt(&ok, 16); } //数值转为字符串 //点击微调框上下按钮时被调用 QString HexSpinBox::textFromValue(int val) const { return QString::number(val, 16).toUpper(); } //main.cpp #include <QApplication> #include "HexSpinBox.h" int main(int argc, char** argv) { QApplication app(argc, argv); HexSpinBox spinBox; spinBox.show(); return app.exec(); } |
下一篇: 无
上一篇: 2.5 动态对话框