2014-11-08 25 views
3

我有一個基於Qt的文本編輯器程序。它的默認主題是黑暗的。我想添加一個功能,當用戶選擇switchtheme()的QAction時,主題應該切換爲亮起,並且圖標也應該根據明暗變化。在我的qrc文件中,我已經設置瞭如下結構:如何根據Qt C++中的主題更改圖標?如果可用的主題是黑暗或光

:/images 
|--> /theme_dark/ 
|--> /theme_light/ 

兩個目錄中的圖標文件名都保持相同。

void MainWindow::switchTheme(const QString &themeName) 
{ 
//themeName will be "light" or "dark" 

    QString image_path = ":/images/theme_"+themeName+"/"; 

    //Now maybe we can create a QStringList and append(filenames) to it. 
    //Find all QActions in the toolbar and setIcon()? 
} 

事情是黑暗的圖標在黑暗的主題看起來不好,光的主題看起來不太好。我想知道如何以有效的方式做到這一點。

回答

4

您可以使用QFileSelector

QFileSelector selector; 
QStringList extraSelectors; 
extraSelectors << "theme_dark"; 
selector.setExtraSelectors(extraSelectors); 
QString image = selector.select(":/images/myImage.png"); 

QRC文件結構應該是:

:/images 
|--> /+theme_dark/ 
|-----> myImage.png 
|--> /+theme_light/ 
|-----> myImage.png 
+0

其實images /目錄裏面,有對工具欄圖標。所以我必須單獨設置 'QAction * act = qobject_cast (ui-> action_Name);' 'act-> setIcon(QIcon(image_path +「image.png」));' 有沒有更快捷的方法呢?也許設置圖像名稱和操作名稱會有所幫助? 例如,在文本編輯器中有工具欄按鈕,當切換主題時,所有工具按鈕也應該改變顏色。 – Bhavyanshu 2014-11-08 12:50:14

+1

@Bhavyanshu您可以使用myToolbar-> [actions()](http://qt-project.org/doc/qt-5/qwidget.html#actions)來獲取所有操作。然後遍歷QList 並設置圖標:setIcon(QIcon(selector.select(「:/ images /」+ actionsList.at(0).title +「。png」)))。在這種情況下,圖片名稱必須與動作標題相同。當您修改主題時,應該更改extraSelectors並重置所有圖標。 – Meefte 2014-11-08 14:44:07

+0

謝謝。得到它了! – Bhavyanshu 2014-11-08 20:26:10

相關問題