Search code examples
c++qtqcombobox

Can QComboBox items text consist of 2 colors?


For example for string "Elon Musk":

  • "Elon" text color is red;
  • "Musk" text color is green;

Thanks in advance for any help you can provide


Solution

  • As an alternative approach to using delegates I would use a QLabel with rich text (HTML encoded) to color the combo box item text. I also need to implement an event filter to handle clicking (selecting) "custom" items. The following example demonstrates how to do it:

    class Filter : public QObject
    {
    public:
      Filter(QComboBox *combo)
        :
          m_combo(combo)
      {}
    protected:
      bool eventFilter(QObject *watched, QEvent * event) override
      {
        auto lbl = qobject_cast<QLabel *>(watched);
        if (lbl && event->type() == QEvent::MouseButtonRelease)
        {
          // Set the current index
          auto model = m_combo->model();
          for (int r = 0; r < model->rowCount(); ++r)
          {
            if (m_combo->view()->indexWidget(model->index(r, 0)) == lbl)
            {
              m_combo->setCurrentIndex(r);
              break;
            }
          }
          m_combo->hidePopup();
        }
        return false;
      }
    
    private:
      QComboBox *m_combo;
    };
    

    And here is how to add "colored" items into combo box and handle them:

    QComboBox box;
    box.setEditable(true);
    Filter filter(&box);
    
    // Add two items: regular and colored.
    box.addItem("A regular item");
    box.addItem("Elon Musk");
    
    // Handle the colored item. Color strings using HTML tags.
    QLabel lbl("<font color=\"red\">Elon </font><font color=\"green\">Musk</font>", &box);
    lbl.setAutoFillBackground(true);
    lbl.installEventFilter(&filter);
    box.view()->setIndexWidget(box.model()->index(1, 0), &lbl);
    
    box.show();