环境配置 Qt Creator 4.6.2+Based on Qt 5.11.1 (MSVC 2015, 32 bit) |
效果图:
其实这个缩略图就是模仿Chrome书签栏拖拽书签时的缩略图(如下图所示)。主要是重写QWidget的paintEvent函数。
thumbnail类继承自QWidget
- thumbnail.h
#ifndef THUMBNAIL_H #define THUMBNAIL_H #include <QWidget> #include <QPushButton> #include <QLabel> #define RADIUS 17 //窗口边角的弧度 #define ELLIPSE_RADIUS 12 //内部小圆半径 #define RECT 10 //图标长/宽的一半 #define TEXT_LENGTH 100 //文字长度 class thumbnail : public QWidget { Q_OBJECT public: thumbnail(QWidget *parent = nullptr); void setupthumbnail(QIcon icon, QString str); void setIconSize(int size); private: QPushButton *ImageButton = nullptr; QLabel *TextLabel = nullptr; private: void initUi(); void paintEvent(QPaintEvent *); }; #endif // THUMBNAIL_H
- thumbnail.cpp
#include "thumbnail.h" #include<QHBoxLayout> #include<QPainter> thumbnail::thumbnail(QWidget *parent) : QWidget(parent) { initUi(); } void thumbnail::initUi() { setWindowFlags(Qt::FramelessWindowHint); setAttribute(Qt::WA_TranslucentBackground); setFixedSize(140, 34); ImageButton = new QPushButton(this); ImageButton->setFixedSize(20, 20); ImageButton->setIconSize(QSize(20, 20)); ImageButton->setFlat(true); ImageButton->setStyleSheet("QPushButton{border:0px solid rgb(0, 0, 0);}"); ImageButton->setFocusPolicy(Qt::NoFocus); ImageButton->move(RADIUS - RECT, RADIUS - RECT);//ImageButton在小圆里 TextLabel = new QLabel(this); TextLabel->setFixedSize(TEXT_LENGTH, 20); TextLabel->setAlignment(Qt::AlignVCenter); TextLabel->setFont(QFont("Microsoft YaHei", 8, QFont::Normal)); TextLabel->setStyleSheet("QLabel{color:rgba(255, 255, 255, 255); border:0px solid rgb(0, 0, 0);}"); TextLabel->setFocusPolicy(Qt::NoFocus); QHBoxLayout *layout = new QHBoxLayout(this); layout->setSpacing(0); layout->addWidget(TextLabel); layout->setContentsMargins(2 * RADIUS, 0, 0, 2); QPixmap a; a.load(":/mus/1193404.gif"); setupthumbnail(QIcon(a),"music"); setIconSize(15); } void thumbnail::setupthumbnail(QIcon icon, QString text) { ImageButton->setIcon(QIcon(icon)); TextLabel->setText(text); int textSize = fontMetrics().width(text); //字符超长检测 if(textSize > TEXT_LENGTH){ QString Elide_text = fontMetrics().elidedText(text, Qt::ElideRight, TEXT_LENGTH); TextLabel->setText(Elide_text); } } void thumbnail::setIconSize(int size) { ImageButton->setIconSize(QSize(size, size)); } void thumbnail::paintEvent(QPaintEvent *) { QPainter Painter(this); Painter.setRenderHint(QPainter::Antialiasing, true);//抗锯齿,反走样 Painter.setPen(Qt::NoPen); Painter.setBrush(QColor(114, 164, 250, 200)); QPainterPath PainterPath; PainterPath.addRoundedRect(QRect(0, 0, width(), height()), RADIUS, RADIUS); //RoundedRect PainterPath.addEllipse(RADIUS - ELLIPSE_RADIUS, RADIUS - ELLIPSE_RADIUS, ELLIPSE_RADIUS * 2, ELLIPSE_RADIUS * 2); //除去内部小圆 Painter.drawPath(PainterPath); Painter.setBrush(QColor(255, 255, 255, 200)); Painter.drawEllipse(RADIUS - ELLIPSE_RADIUS, RADIUS - ELLIPSE_RADIUS, ELLIPSE_RADIUS * 2, ELLIPSE_RADIUS * 2); //内部小圆重新上色 }
所用到的图片
转载:https://blog.csdn.net/weixin_43742643/article/details/100567831