Hello,阳光柠檬! 养成记录笔记的好习惯

Qt中用QSS切分图片

2016-07-02
Qt

Qt设计时有时需要实现动态按钮,按钮点击时一个状态,鼠标悬浮时一个状态,离开时一个状态,静止时一个状态。可以用一张png长图,使用QSS分段截取,分配给每一个状态。

这里写图片描述

这里写图片描述

这里写图片描述

函数调用

    SetButtonStyle(ui->flashButton,":/images/button.png",4);//Qss切割图片

函数声明

void Widget::SetButtonStyle(QPushButton *button, QString imgsrc, int CutSec)
{
    //=========================Qss切割图片
    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-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));
}

直接写样式表(一个28x28的Button, 2.png为112x28的图)

QPushButton{
border-image: url(:/res/2.png)  0 0 0 0 repeat  repeat;
border-width: 0px;
border-radius: 0px;
}
QPushButton::hover{
border-image: url(:/res/2.png) 0 0 0 28  repeat  repeat;
}
QPushButton::pressed{
border-image: url(:/res/2.png) 0  0 0 56 repeat  repeat;
}
QPushButton::disabled{
border-image: url(:/res/2.png) 0  0 0 84 repeat  repeat;
}

下一篇 Git常用命令

Comments

Content