平铺背景控件,主要的应用场景是做为画布出现,黑白相间的背景图,而后上面能够放置图片图形等,使得看起来更美观,好比PS软件新建图层之后的背景,FireWorks软件新建画布之后的透明背景,ICO制做软件新建画布之后的背景,都会采用一个黑白相间的背景。尽管本人用QPainter不少年,后面在翻阅QPainter自带的函数中才发现竟然QPainter自带了这个绘制平铺背景的函数,擦,他么叫drawTiledPixmap,Qt不愧是跨平台GUI开发中的佼佼者,这些东西竟然都考虑到了,说到考虑的周到,Qt中连size和count和length都完美的封装了,适合不一样人群的使用习惯,这个考虑也是很是周到的。drawTiledPixmap就两个参数,第一个参数是要绘制的区域,第二个参数是要绘制的图片,图片不足会自动拷贝填充,因此若是提供的是两个交替颜色的背景图片,就会依次绘制造成平铺背景的效果,为了使得颜色能够控制,本控件增长了交替颜色的设置,能够自行传入两种颜色做为交替颜色,在程序内部自动生成要绘制的图片。linux
#ifndef TILEDBG_H #define TILEDBG_H /** * 平铺背景控件 做者:feiyangqingyun(QQ:517216493) 2018-8-25 * 1:可设置交替背景颜色 */ #include <QWidget> #ifdef quc #if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) #include <QtDesigner/QDesignerExportWidget> #else #include <QtUiPlugin/QDesignerExportWidget> #endif class QDESIGNER_WIDGET_EXPORT TiledBg : public QWidget #else class TiledBg : public QWidget #endif { Q_OBJECT Q_PROPERTY(QColor color1 READ getColor1 WRITE setColor1) Q_PROPERTY(QColor color2 READ getColor2 WRITE setColor2) Q_PROPERTY(QPixmap bgPix READ getBgPix WRITE setBgPix) public: explicit TiledBg(QWidget *parent = 0); protected: void drawBg(); void paintEvent(QPaintEvent *); private: QColor color1; //颜色1 QColor color2; //颜色2 QPixmap bgPix; //背景图片 public: QColor getColor1() const; QColor getColor2() const; QPixmap getBgPix() const; QSize sizeHint() const; QSize minimumSizeHint() const; public slots: //设置颜色1 void setColor1(const QColor &color1); //设置颜色2 void setColor2(const QColor &color2); //设置背景图片 void setBgPix(const QPixmap &bgPix); }; #endif // TILEDBG_H
#pragma execution_character_set("utf-8") #include "tiledbg.h" #include "qpainter.h" #include "qdebug.h" TiledBg::TiledBg(QWidget *parent) : QWidget(parent) { color1 = QColor(255, 255, 255); color2 = QColor(220, 220, 220); bgPix = QPixmap(64, 64); drawBg(); } void TiledBg::drawBg() { bgPix.fill(color1); QPainter painter(&bgPix); painter.fillRect(0, 0, 32, 32, color2); painter.fillRect(32, 32, 32, 32, color2); painter.end(); update(); } void TiledBg::paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawTiledPixmap(this->rect(), bgPix); } QColor TiledBg::getColor1() const { return this->color1; } QColor TiledBg::getColor2() const { return this->color2; } QPixmap TiledBg::getBgPix() const { return this->bgPix; } QSize TiledBg::sizeHint() const { return QSize(100,100); } QSize TiledBg::minimumSizeHint() const { return QSize(20,20); } void TiledBg::setColor1(const QColor &color1) { if (this->color1 != color1) { this->color1 = color1; drawBg(); } } void TiledBg::setColor2(const QColor &color2) { if (this->color2 != color2) { this->color2 = color2; drawBg(); } } void TiledBg::setBgPix(const QPixmap &bgPix) { this->bgPix = bgPix; update(); }