当前位置:   article > 正文

自定义Qt窗口部件_qvalidator::state validate(qstring &text, int &pos

qvalidator::state validate(qstring &text, int &pos) const;

根据C++GUI Qt4编程(第二版)

本程序实现一个十六进制微调窗并演示

hexspinbox.h文件

  1. #ifndef HEXSPINBOX_H
  2. #define HEXSPINBOX_H
  3. #include <QSpinBox>
  4. class QRegExpValidator;
  5. class HexSpinBox : public QSpinBox
  6. {
  7. Q_OBJECT
  8. public:
  9. explicit HexSpinBox(QWidget *parent = 0);
  10. protected:
  11. QValidator::State validate(QString &input, int &pos) const;
  12. int valueFromText(const QString &text) const;
  13. QString textFromValue(int val) const;
  14. private:
  15. QRegExpValidator*validator;
  16. };
  17. #endif // HEXSPINBOX_H

hexspinbox.cpp文件
  1. #include "hexspinbox.h"
  2. #include <QtGui>
  3. #include <QRegExpValidator>
  4. HexSpinBox::HexSpinBox(QWidget *parent) :
  5. QSpinBox(parent)
  6. {
  7. setRange(0,255);
  8. validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"),this);
  9. }
  10. QValidator::State HexSpinBox::validate(QString &input, int &pos) const
  11. {
  12. return validator->validate(input,pos);
  13. }
  14. int HexSpinBox::valueFromText(const QString &text) const
  15. {
  16. bool ok;
  17. return text.toInt(&ok,16);
  18. }
  19. QString HexSpinBox::textFromValue(int val) const
  20. {
  21. return QString::number(val,16).toUpper();
  22. }

然后就可以使用这个十六进制部件,在一个QDialog放置自定义的HexSpinBox,再放一个QLabel显示它对应的十进制。

dialog.h

  1. #ifndef DIALOG_H
  2. #define DIALOG_H
  3. #include <QDialog>
  4. #include <hexspinbox.h>
  5. class QLabel;
  6. class Dialog : public QDialog
  7. {
  8. Q_OBJECT
  9. public:
  10. explicit Dialog(QWidget *parent = 0);
  11. private:
  12. QLabel *lb;
  13. HexSpinBox *hexSpinBox;
  14. private slots:
  15. void showValue(int val);
  16. };
  17. #endif // DIALOG_H

dialog.cpp

  1. #include "dialog.h"
  2. #include <QtGui>
  3. Dialog::Dialog(QWidget *parent) :
  4. QDialog(parent)
  5. {
  6. QHBoxLayout *hBoxLayout = new QHBoxLayout;
  7. hexSpinBox=new HexSpinBox;
  8. lb = new QLabel;
  9. hBoxLayout->addWidget(hexSpinBox);
  10. hBoxLayout->addWidget(lb);
  11. setLayout(hBoxLayout);
  12. connect(hexSpinBox,SIGNAL(valueChanged(int)),this,SLOT(showValue(int)));
  13. }
  14. void Dialog::showValue(int val)
  15. {
  16. lb->setText(QString::number(val,10));
  17. }


主函数:

  1. #include <QApplication>
  2. #include <dialog.h>
  3. int main(int argc,char*argv[])
  4. {
  5. QApplication app(argc,argv);
  6. Dialog *dlg = new Dialog;
  7. dlg->show();
  8. return app.exec();
  9. }

显示效果图:


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/115080
推荐阅读
相关标签
  

闽ICP备14008679号