效果如下:
实现有如下几种方式:
1. 使用 QPushButton 设置 setStyleSheet
例:
ui->recorder->setStyleSheet("QPushButton{"\
"border: 1px solid #00d2ff; "\
"min-height: 60px; "\
"color: #FFFFFF;; "\
"font-size:16px; "\
"text-align : bottom; "\
"background-image: url(:/record.png);"\
"background-repeat: repeat-no-repeat;"\
"background-position: top;"\
"background-origin:content;"\
"padding: 10px;"\
"background-color: rgb(0, 0, 0);"\
"}");
2.QPushButton用qss自定义设置上图标下文字的样式
QPushButton#pushButton_recorder{
padding-top: 2px;
padding-bottom: 2px;
padding-left: 4px;
padding-right: 4px;
border: none;
font: bold 16px;
color: #FFFFFF;
text-align:bottom;
border-radius: 6px;
background-color: #000000;
background-image: url(:/images/recorder.png);
background-position: top;
background-origin: content;
background-repeat: no-repeat;
)
3.使用QToolButton设置Qt::ToolButtonTextUnderIcon
ui->toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
qss样式设置:
QToolButton#toolButtonRecorder {
qproperty-icon:url(:/images/recorder.png);
qproperty-iconSize: 40px 40px;
border: 1px solid transparent;
border-radius: 15px;
background-color: transparent;
font-size: 16px;
color:#0B68D0;
border-radius: 6px;
background-color: #FFFFFF;
}
4. 自定义 QPushButton 代码重写 QPushButton类自定义上图标下文字的按钮控件类
void MyPushButton::drawIcon(QPainter *painter)
{
const QRect btnRect = QRect(10, 10, 80, 80);
const QSize iconSize = QSize(40, 40);
QPixmap pix(":/images/close.png");
painter->save();
painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
painter->drawPixmap(QRect((btnRect.width() - iconSize.width() ) / 2,
6,
iconSize.width(),
iconSize.height()),
pix);
painter->restore();
}
void MyPushButton::drawText(QPainter *painter)
{
const QRect btnRect = QRect(10, 10, 80, 80);
const QSize iconSize = QSize(40, 40);
painter->save();
painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
QFont font = this->font();
font.setPixelSize(16);
painter->setFont(font);
painter->drawText(QRect( 0,
(6 + iconSize.height()),
btnRect.width(),
(btnRect.height() - (6 + iconSize.height()))),
Qt::AlignCenter,
"关闭");
painter->restore();
}
void MyPushButton::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QStyleOption opt;
opt.init(this);
style()->drawPrimitive(QStyle::PE_Widget,&opt, &painter, this);
QPushButton::paintEvent(event);
drawIcon(&painter);
drawText(&painter);
}