【发布时间】:2018-11-23 13:49:57
【问题描述】:
例如字符串“Elon Musk”:
- “Elon”文本颜色为红色;
- “Musk”文本颜色为绿色;
提前感谢您提供的任何帮助
【问题讨论】:
-
你可以看看这个答案:stackoverflow.com/a/2039745/6165833
例如字符串“Elon Musk”:
提前感谢您提供的任何帮助
【问题讨论】:
作为使用委托的另一种方法,我将使用带有富文本(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();
【讨论】:
是的,可以。事实上,您可以使用QItemDelegate 在其中做任何您想做的事情。在代理内部,你可以做所有你想做的疯狂的事情,不仅包括着色,还包括按钮和其他控件。
【讨论】:
QStyledItemDelegate 是文档推荐的,而不是QItemDelegate。
您可以使用 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();
}
截图供参考 -
【讨论】: