QPushButton 灵活设置Icon 和文案

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,大功告成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值