Reputation: 53
For example for string "Elon Musk":
Thanks in advance for any help you can provide
Upvotes: 4
Views: 560
Reputation: 21248
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();
Upvotes: 1
Reputation: 1020
You can play with Qt::ItemDataRole to provide customisations. For this particular case -
#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();
}
Screenshots for reference -
Upvotes: 1
Reputation: 26356
Yes, it can. In fact you can do whatever you want in there using QItemDelegate. Inside the delegate you can do all the crazy stuff you want, which not only includes coloring, but also buttons and other controls.
Upvotes: 1