Qt自绘系列
一、自定义状态笑脸
其中笑脸是png图片,通过drawPixmap,右边字体通过drawText
ZStateText.h
#ifndef ZSTATETEXT_H #define ZSTATETEXT_H #include <QWidget> #include "includes.h" #include <QPixmap> class QToolButton; class ZStateText : public QWidget { Q_OBJECT public: explicit ZStateText(QWidget *parent = nullptr); /*设置类型并重绘*/ inline void setType(const BIT_State_Type& type){m_type=type;reDraw();} /*设置颜色和字体*/ inline void setInfo(const QString& name, const QString& color){m_name=name;m_color.setNamedColor(color);reDraw();} inline void setText(const QString&text){m_name=text;} inline void setTextColor(const QString& color){m_color.setNamedColor(color);} inline void setPngPath(const QString& pngPath){m_png_path = pngPath;} /*重绘*/ inline void reDraw(){this->update();} signals: protected: /*绘制*/ void paintEvent(QPaintEvent *) override; public slots: private: int m_width = 26; BIT_State_Type m_type = BIT_State_OK; QColor m_color; QString m_name; QString m_png_path = ""; private: int __margin = 0; }; #endif // ZSTATETEXT_H
ZStateText.cpp
#include "zstatetext.h" #include <QPainter> #include <QPixmap> ZStateText::ZStateText(QWidget *parent) : QWidget(parent) { m_color.setNamedColor("#A8A8A8"); m_name = "离线/未知"; } void ZStateText::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); painter.setPen(QPen(m_color)); painter.setBrush(m_color); QFont font; font.setFamily("Microsoft YaHei"); painter.setFont(font); QRect textRect(m_width*2, 0, m_width*3, m_width); painter.drawText(textRect, Qt::AlignVCenter | Qt::AlignHCenter, m_name); if("" == m_png_path){ painter.drawEllipse(QPointF(m_width, m_width/2+1), m_width/2-__margin, m_width/2-__margin); }else{ QPixmap pix(m_png_path); painter.drawPixmap(0, 0, 30, 30, pix); } }
长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html