现在的位置: 首页 > 综合 > 正文

自定义Qt窗口部件

2012年09月13日 ⁄ 综合 ⁄ 共 1764字 ⁄ 字号 评论关闭

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

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

hexspinbox.h文件

#ifndef HEXSPINBOX_H
#define HEXSPINBOX_H

#include <QSpinBox>
class QRegExpValidator;

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;
private:
    QRegExpValidator*validator;
};

#endif // HEXSPINBOX_H

hexspinbox.cpp文件

#include "hexspinbox.h"
#include <QtGui>
#include <QRegExpValidator>

HexSpinBox::HexSpinBox(QWidget *parent) :
    QSpinBox(parent)
{
    setRange(0,255);
    validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"),this);
}

QValidator::State HexSpinBox::validate(QString &input, int &pos) const
{
    return validator->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();
}

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

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <hexspinbox.h>
class QLabel;
class Dialog : public QDialog
{
    Q_OBJECT
public:
    explicit Dialog(QWidget *parent = 0);
private:
    QLabel *lb;
    HexSpinBox *hexSpinBox;
private slots:
    void showValue(int val);
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include <QtGui>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent)
{
    QHBoxLayout *hBoxLayout = new QHBoxLayout;
    hexSpinBox=new HexSpinBox;
    lb = new QLabel;
    hBoxLayout->addWidget(hexSpinBox);
    hBoxLayout->addWidget(lb);

    setLayout(hBoxLayout);
    connect(hexSpinBox,SIGNAL(valueChanged(int)),this,SLOT(showValue(int)));
}

void Dialog::showValue(int val)
{
    lb->setText(QString::number(val,10));
}

主函数:

#include <QApplication>
#include <dialog.h>

int main(int argc,char*argv[])
{
    QApplication app(argc,argv);
    Dialog *dlg = new Dialog;
    dlg->show();
    return app.exec();
}

显示效果图:

抱歉!评论已关闭.