失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Qt QPushButton背景图片

Qt QPushButton背景图片

时间:2021-12-03 04:27:25

相关推荐

Qt QPushButton背景图片

一、问题

使用控件显示图片缩略图,当点击控件时,弹出窗口显示完整的图片

二、分析

应该用按钮控件,用信号槽连接。按钮控件是有参数icon,但是只能显示控件中,不能覆盖在整个控件上。

三、方法一:使用styleSheet

1、代码段

QString imgPathStr = ":/images/Qt.png"; // 背景图片文件路径QString styleSheet = QString("QPushButton{border-image: url(%1);}").arg(imgPathStr); QPushButton *btn = new QPushButton(this); btn->setStyleSheet(styleSheet);QImage img(imgPathStr); int w = img.width(); int h = img.height(); // 图片宽高等比例缩放int maxSide = 100;// 调整图片中宽高最大者至maxSide if(w >= h){double scale = maxSide / double(w); w = maxSide; h *= scale; }else{double scale = maxSide / double(h); h = maxSide; w *= scale; } btn->setFixedSize(w,h);

2、效果图
3、 注意

控件适合自己所要大小,对图片进行长宽等比缩放计算,得到最终长宽,将控件设为固定长宽。

四、 方法二:继承QPushButton重写paintEvent

1、代码段

// 继承QPushButton重写paintEventclass ImageButton : public QPushButton{public: ImageButton(QWidget *parent = 0):QPushButton(parent){} void setImage(QPixmap pixMap){_pixMap = pixMap; setFixedSize(_pixMap.size()); }protected: void paintEvent(QPaintEvent* event){QPainter painter(this); painter.drawPixmap(rect(), _pixMap); }private: QPixmap _pixMap;};// 调用QString imgPathStr = ":/images/Qt.png"; // 背景图片文件路径QImage img(imgPathStr);QImage scaledImg = img.scaled(100,100,Qt::KeepAspectRatio,Qt::SmoothTransformation);ImageButton *btn = new ImageButton(this);btn->setImage(QPixmap::fromImage(scaledImg));

五、附加

前面主要讲了图片如何在QPushButton上显示,至于点击后显示完整图片就很简单了。

1、代码段

connect(btn,&QPushButton::clicked,this,[=](){QDialog dlg(this);QHBoxLayout *hLay = new QHBoxLayout(&dlg);QLabel *label = new QLabel(&dlg);label->setPixmap(QPixmap::fromImage(img));hLay->addWidget(label);dlg.exec();});

2、注意

这里用了匿名函数,也可以将匿名函数函数体提取然后做些修改创建成槽函数

对你有用就点个赞👍,以后需要用到就收藏⭐

如果觉得《Qt QPushButton背景图片》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。