c++ - QComboBox 项目文本可以包含 2 种颜色吗?

标签 c++ qt qcombobox

例如字符串“Elon Musk”:

  • “Elon”文字颜色为红色;
  • “麝香”文字颜色为绿色;

在此先感谢您提供的任何帮助

最佳答案

作为使用委托(delegate)的替代方法,我将使用带有富文本(HTML 编码)的 QLabel 来为组合框项目文本着色。我还需要实现一个事件过滤器来处理单击(选择)“自定义”项目。以下示例演示了如何操作:

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;
};

下面是如何将“彩色”项目添加到组合框中并处理它们:

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();

关于c++ - QComboBox 项目文本可以包含 2 种颜色吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53447944/

相关文章:

C++ 对象创建时没有使用 new 关键字,但在构造函数中使用了 new 关键字

c++ - 使用 `void*` 将右值引用绑定(bind)到左值

qt - 如何使用 C++ 将 ITK 连接到 VTK?

python - 在 PyQt 中,在主窗口和线程之间共享数据的最佳方式是什么

python - PyQT按钮点击不起作用

qt5 - QComboBox 省略了所选项目上的文本

python - 获取由单独的类方法/函数中的事件触发的 QComboBox 项目文本

c++ - 如何使用 OpenMP 屏障

pyqt - 键/值 pyqt QComboBox

c++ - 如何加快将文本文件加载到多 vector