Qt 界面使用自己定義控件 "提升為"


1.效果圖


我做了一個很easy的樣例,一個能夠顯示顏色的QLabel,邊上有個button,點擊,跳出顏色選取的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 界面使用自己定義控件



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM