QPushButton 灵活设置Icon 和文案
QPushButton 有多种设置 Icon 和文案方法,但有的方式并不是很灵活,不能设置Icon 与文案的距离。比如下面这段代码
void InitBtnView()
{
QPushButton* btn = new QPushButton(this);
btn ->setText("More");
btn ->setLayoutDirection(Qt::RightToLeft);
btn ->setIcon(QIcon(QString("/Application/icon_back_nor")));
btn ->setStyleSheet(QString("QPushButton{ background-color:#2e3947;font-weight: 400; font-size: 14px; color:rgba(255, 255, 255, 0.8);text-align: left; border-radius: 8px; padding: 0px 8px 0px 8px;}\
QPushButton::hover{ background-color: %1;padding: 0px 8px 0px 8px;}").arg(MAINCOLOR));
btn ->setIconSize(QSize(16, 16));
btn ->setFixedSize(btn ->sizeHint().width() + 4, 36);
}
上述代码可以处理比较简单的情况,但是较为复杂的情况就显得捉襟见肘了,比如文案要考虑多语言,Icon 与文案的距离就不能自适应了。下面采用更灵活的方式
void InitBtnView(bool bHover)
{
QPushButton* btn = new QPushButton(this);
QLabel* textLabel = new QLabel(btn);
QLabel* IconLabel = new QLabel(btn);
QHBoxLayout* pLayout = new QHBoxLayout(btn);
pLayout->setContentsMargins(0, 0, 0, 0);
IconLabel ->setFixedSize(QSize(16, 16));
textLabel ->setFixedHeight(36); // 按钮的高度
pLayout->addWidget(textLabel);
pLayout->addWidget(IconLabel);
pLayout->setAlignment(Qt::AlignCenter);
btn ->setLayout(pLayout);
if (bHover)
{
IconLabel ->setStyleSheet(QString("QLabel{background-color: transparent;border-image: url(%1);}").arg("/Application/icon_more_hov"));
textLabel ->setStyleSheet(QString("QLabel{background-color: transparent;font-weight: 600;font-size: 14px; color:#FFFFFF;}"));
}
else
{
IconLabel ->setStyleSheet(QString("QLabel{background-color: transparent;border-image: url(%1);}").arg("/Application/icon_more_nor"));
textLabel ->setStyleSheet(QString("QLabel{background-color: transparent;font-weight: 600;font-size: 14px; color:%1;}").arg(MAINCOLOR));
}
}
OK,大功告成了!