Qt 界面使用自定义控件 "提升为"

1.效果图


我做了一个非常简单的例子,一个可以显示颜色的QLabel,边上有个按钮,点击,跳出颜色选取的Dialog,然后选择一个颜色,这个QLabel会变成什么颜色。


2.ColorLabel 


我们先把这个自定义的类写好:

头文件:

#ifndef COLORLABEL_H
#define COLORLABEL_H

#include <QLabel>
#include <QPainter>

class ColorLabel : public QLabel{
    Q_OBJECT
public:
    explicit ColorLabel(QWidget *parent=0);
    void setColor(QColor c);
private:
    QColor color;
    QPainter *paint;
    void paintEvent(QPaintEvent *);
};


#endif // COLORLABEL_H

实现文件:

#include "colorlabel.h"


ColorLabel::ColorLabel(QWidget *parent):QLabel(parent), color(Qt::white){
}

void ColorLabel::paintEvent(QPaintEvent *){
    paint = new QPainter;
    paint->begin(this);
    paint->setBrush(QBrush(color,Qt::SolidPattern));
    paint->drawRect(0, 0, this->geometry().width(), this->geometry().height());
    paint->end();
}

void ColorLabel::setColor(QColor c){
    color = c;
}




3.界面文件里添加ColorLabel

拖一个普通的QLabel到界面文件里,然后右击这个控件,选择提升为。



输入类名称,就OK了。


我们可以去Qt根据布局文件生成的头文件里面看下,它自己包含了colorlabel.h,把QLabel都改成了ColorLabel。


Qt写起来真是不错。


4.本博文例子下载:

http://www.waitingfy.com/?attachment_id=1170



参考:

Qt 界面使用自定义控件


猜你喜欢

转载自blog.csdn.net/fox64194167/article/details/31018451