【问题标题】:Can QComboBox items text consist of 2 colors?QComboBox 项目文本可以包含 2 种颜色吗?
【发布时间】:2018-11-23 13:49:57
【问题描述】:

例如字符串“Elon Musk”:

  • “Elon”文本颜色为红色;
  • “Musk”文本颜色为绿色;

提前感谢您提供的任何帮助

【问题讨论】:

标签: c++ qt qcombobox


【解决方案1】:

作为使用委托的另一种方法,我将使用带有富文本(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();

【讨论】:

    【解决方案2】:

    是的,可以。事实上,您可以使用QItemDelegate 在其中做任何您想做的事情。在代理内部,你可以做所有你想做的疯狂的事情,不仅包括着色,还包括按钮和其他控件。

    【讨论】:

    • 感谢您的回复。我不确定在哪里更改颜色,但我将在 QStyledItemDelegate 的子类化方向和paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) 方法的重新实现方向上进行搜索。所以改变“选项”我希望能解决我的问题
    • QStyledItemDelegate 是文档推荐的,而不是QItemDelegate。
    【解决方案3】:

    您可以使用 Qt::ItemDataRole 来提供自定义。对于这种特殊情况 -

    #include <QApplication>
    #include <QComboBox>
    #include <QColor>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QComboBox box;
        box.addItem("Elon");
        box.addItem("Musk");
    
        box.setItemData(0, QColor(Qt::red), Qt::ForegroundRole);
        box.setItemData(1, QColor(Qt::green), Qt::ForegroundRole);
    
        box.show();
    
        return a.exec();
    }
    

    截图供参考 -

    【讨论】:

    • 这么详细的回答,非常感谢。但是对我的问题给出了令人困惑的描述,对此感到抱歉。我的意思是:“埃隆马斯克”是一项(不是两项)
    • 但问题是关于在单个项目中为字符串着色。 IE。 “Elon Musk”是单个项目中的文本,其中“Elon (red) Musk (green)”。
    猜你喜欢
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    相关资源
    最近更新 更多