方法一:QPushButton用qss自定义设置上图标下文字的样式
QPushButton#pushButton_close{
padding-top: 2px;
padding-bottom: 2px;
padding-left: 4px;
padding-right: 4px;
border: none;
font: bold 16px;
color: #0B68D0;
text-align:bottom;
border-radius: 6px;
background-color: #FFFFFF;
background-image: url(:/images/close.png);
background-position: top;
background-origin: content;
background-repeat: no-repeat;
方法二:使用QToolButton设置Qt::ToolButtonTextUnderIcon
ui->toolButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
qss样式设置:
QToolButton#toolButton {
qproperty-icon:url(:/images/close.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;
}
方法三:重写QPushButton类自定义上图标下文字的按钮控件类文章来源:https://www.toymoban.com/news/detail-729198.html
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);
}
参考效果:
文章来源地址https://www.toymoban.com/news/detail-729198.html
到了这里,关于Qt:上图标下文字的按钮的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!