天天看點

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.效果

繼續閱讀