天天看点

Qt之按钮左边图标右边文字(转)

一.前言

软件开发过程中,会遇到这样的需求,一个按钮要携带图标和文字,且图标在左,文字在右,以此来增强这个按钮的功能指向,这个样式在移动端还是蛮常见的,最典型就是搜索栏。

二、在Qt中有两种方式可以实现需求

方式一:代码方式

1.核心代码

`

ui->pushButton->setIcon(QIcon(":/buttonIcon.png"));

ui->pushButton->setLayoutDirection(Qt::LeftToRight);

ui->pushButton->setText("左边图标,右边文字");      

`

2.效果

Qt之按钮左边图标右边文字(转)

3.关于setLayoutDirection

官方文档是这样的:

This property holds the layout direction for this widget

By default, this property is set to Qt::LeftToRight.

When the layout direction is set on a widget, it will propagate to the widget’s children, but not to a child that is a window and not to a child for which setLayoutDirection() has been explicitly called. Also, child widgets added after setLayoutDirection() has been called for the parent do not inherit the parent’s layout direction.

大概的意思,就是这个函数是设置控件的布局方向,默认是设置从左到右的(因此在代码中,其实我们也可以不用设置,也可以实现效果),当控件设置了这个布局方向之后,他是传递到没有显示调用setLayoutDirection的子控件的,但是不会传递到作为窗口的控件,有点像向下传递而不向上传递;还有一个就是如果父控件先调用setLayoutDirection,后面再添加其他子控件,子控件是不会继承父控件的布局方向的,所以为了严谨,建议还是把setLayoutDirection加在需要设置左图标右文字的控件属性上,免得受其他控件的影响

方式二:样式表

1.核心代码以及备注

核心是样式文件的编写,这里为了简单直接在代码里面写

`

// 方式2

ui->pushButton->setText("左边图标,右边文字");

QStringList qssList;      
// 根据需要配置
qssList.append("height: 35px;");
qssList.append("font-size: 14pt");

// 图标路径
qssList.append("background-image: url(:/buttonIcon.png);");

// 固定编写
qssList.append("background-repeat: no-repeat;");
qssList.append("background-origin: padding;");
qssList.append("background-position: left;");
qssList.append("text-align:left;");

// 这里根据实际去调整参数,因为涉及到图标的大小,这里经过测试合适的为22%,可以用百分比或者像素px实现
qssList.append("padding-left:22%;");

ui->pushButton->setStyleSheet(qssList.join(";"));      

`

4.效果

继续阅读