效果图:
其实这个缩略图就是模仿Chrome书签栏拖拽书签时的缩略图(如下图所示)。主要是重写QWidget的paintEvent函数。
thumbnail类继承自QWidget
thumbnail.h文件
#define RADIUS 17 //窗口边角的弧度#define ELLIPSE_RADIUS 12//内部小圆半径#define RECT 10//图标长/宽的一半#define TEXT_LENGTH 100 //文字长度class thumbnail : public QWidget{Q_OBJECTpublic: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 *);};
thumbnail.c文件
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);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);}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); //RectPainterPath.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); //内部小圆重新上色}