# 更改各種 Qt5 元件的 StyleSheet
## 前言
在 Qt 中有許多各種不同的元件可供使用者去建造出理想的 UI ,而在建立自己的 UI 時,也一定會對於原本的外觀感到不滿,而會想要自己更改這些元件的外觀。不過在 Qt 中,因為它使用的介面設計適用 Xml 與 CSS ,所以一開始在更改某些元件的外觀時,可能會有一些困難。而我這整理了一些元件更改外觀的方法。
## 物件的 ToolTip
首先是幾乎所有物件都有的 ToolTip,也是物件的工具提示。
這是更改前的外觀:

三角形箭頭是Qt按鈕(QPushButton),而這個按鈕的元件名稱為(floorAscButton)。
所以假如我要更改這個元件的 ToolTip 的外觀則要這樣打:

這裡要有一些 CSS 的觀念才比較看得懂!
(QPushButton) 為這裡宣告的元件
(#floorAscButton) 為這個元件的名稱(name)
(QToolTip) 為這個 QPushButton 下的另一個 Qt 元件
```
QPushButton#floorAscButton QToolTip{
background-color: white;
color: rgb(0, 153, 255);
}
```
在來是結果:

---
## 進度條 Progress Bar
進度條是在許多 GUI 中都會用到的物件之一,而在原本的進度條 Style 中會有以下的效果:

假如更改他的 Style 則會讓這種下果消失,就像下圖這樣:

而這時我們可以用程式去模擬出類似的效果,以下是程式碼:
Python
```python=
self._mRunner = 0.1
self._barTimer = QTimer( self )
self._barTimer.timeout.connect( self._updateProgress )
self._barTimer.start(20)
```
```python=
# 更新進度條
def _updateProgress( self ):
if ( self._mRunner >= 0.99 ):
self._upFlag = True
elif( self._mRunner <= 0.01 ):
self._upFlag = False
self._mRunner += -0.01 if self._upFlag else 0.01
color = "#33cd3b" if self._isExceed == False else "#e5070f"
self._diskCapacityBar.setStyleSheet( "background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 {color}, stop: {arg} #e1e1e1, stop:1 {color});".format( arg=str(self._mRunner) , color=color) )
```
C++
```c=
mRunner = 0.1;
QTimer *mTimer = new QTimer(this);
connect(mTimer, SIGNAL(timeout()), this, SLOT(updateProgress()));
mTimer->start(40);
```
```c=
void MainWindow::updateProgress()
{
QString lStyle = QString("QProgressBar::chunk {background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:%1 white, stop:1 #b4b4b4);}").arg(mRunner);
ui->progressBar->setStyleSheet(lStyle);
mRunner += 0.01;
if (mRunner > 1) {
mRunner = 0.1;
}
}
```
這樣打之後就可更改 Style 的情況下還保有波紋效果的進度條。
參考: [How to change color of default style for progressbar in Qt](https://stackoverflow.com/questions/46308990/how-to-change-color-of-default-style-for-progressbar-in-qt) (From Stack Overflow)
###### tags: `Qt5`