Use of Qt standard icons from within Qt Creator

后端 未结 3 1980
甜味超标
甜味超标 2021-02-05 07:38

I would like to use the Qt Standard icons (as here). I have found many examples how to set the icons programmatically (runtime in code).

However, how could I se

3条回答
  •  执念已碎
    2021-02-05 08:22

    @ypnos suggested a great link with multiple approaches to solve the problem. I favorite the last one - Creating a custom icon theme. The author states three Pros (Available to all platforms, Excellent resizing, Covers all needed icons), and two Cons (Not consistent with system icon theme, Pain in the ass to implement). Here I suggest improvements to get rid of the Cons.

    I've cloned the Tango iconset from github. Repository https://github.com/ppinard/qtango already features the index.theme file. But mainly, it brings a Python script generate_rcc.py, which can generate the *.qrc file automatically. I just had to change the arguments of subprocess.check_call() from '--binary' and '--compress' to '-binary' and '-compress'. The generated file contained absolute paths, but that's easy to Find&Replace. One can use this script to any iconset - first laborious step is solved.

    Now, using the "Theme" property, you can define the icons in the Qt Designer, as already shown in the question. For those developing under Linux, system icons will show right in the Designer (suppose the iconset uses standard icon names). That's the native look (icons will be configurable in your system settings). That frees you from the ui->action_Open->setIcon(...) coding.

    And the final tweak is to set the theme before ui setup.

    MainWindow::MainWindow(QWidget *parent) :
      QMainWindow(parent)
    {
    #ifdef _WIN32
      QIcon::setThemeName("tango");
    #endif
    
      ui = new Ui::MainWindow;
      ui->setupUi(this);
    
      ...
      // NO NEED FOR ui->action_Open->setIcon(...)
    }
    

    The #ifdef can of course be adjusted to target all needed platforms, or omitted to force the same icons on all platforms including Linux.

    As a result, this approach avoids all laborious coding and the result is consistent with the system icons at least on Linux.

提交回复
热议问题