QT实现图片按钮(用qss切割图片,或者放三张图片)
我在网上找了很久,把他综合了一下
不说了关键代码来了;(这是一张图片切图的效果)
- void SetButtonStyle(QPushButton *button, QString imgsrc, int CutSec)
- {
- int img_w=QPixmap(imgsrc).width();
- int img_h=QPixmap(imgsrc).height();
- int PicWidth = img_w/CutSec;
- button->setFixedSize(PicWidth,img_h);
- button->setStyleSheet(QString("QPushButton{border-width: 41px; border-image: url(%1) 0 0 0 %2 repeat repeat;border-width: 0px; border-radius: 0px;}")
- .append("QPushButton::hover{border-image: url(%1) 0 0 0 %3 repeat repeat;}")
- .append("QPushButton::pressed{border-image: url(%1) 0 0 0 %4 repeat repeat;}")
- .append("QPushButton::checked{border-image: url(%1) 0 0 0 %4 repeat repeat;}")
- .append("QPushButton::disabled{border-image: url(%1) 0 0 0 %5 repeat repeat;}")
- .arg(imgsrc).arg(0).arg(PicWidth*1).arg(PicWidth*2).arg(PicWidth*3));
- }
调用
- SetButtonStyle(ui->pushButton,":/btn/image/btn.png",4);
效果图
(资源)
还有一种方式就是三张独立的图片
- ui->pushButton->setStyleSheet("QPushButton{border-image: url(:/btn/image/1.png);}"
- "QPushButton:hover{border-image: url(:/btn/image/3.png);}"
- "QPushButton:pressed{border-image: url(:/btn/image/2.png);}");