[Solved] QListview - alter font of one line dynamically
-
wrote on 19 Nov 2013, 09:32 last edited by
I have a QListView, happily showing the contents of a model. The user can select items, and onDoubleClick() makes things happen. It would be nice if the user had some extant way of knowing what they had double-clicked last given that they can change the selection with single-click after having done so, and an obvious way to do this is to make whatever line was last double-clicked bold.
How can I do this? Am I going to have to subclass QListView and make my own paint function or some such?
-
You would have to do the drawing of the text yourself in a delegate subclass.
Try this and check if it fits your needs:
@
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//draw background and selection-highlighting
#if QT_VERSION < 0x050000
QStyleOptionViewItemV4 opt(*qstyleoption_cast<const QStyleOptionViewItemV4 *>(&option));
#else
QStyleOptionViewItem opt = option;
#endifthis->initStyleOption(&opt, index); QString text = opt.text; opt.text = ""; const QWidget *widget = opt.widget; QStyle *style = widget ? widget->style() : QApplication::style(); style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget); QFont font = opt.font; if( ... ) //your condition to decide if you want to draw bold text or not font.setBold(true); painter->save(); painter->setRenderHints(QPainter::TextAntialiasing); painter->setFont(font); painter->drawText( option.rect, text ); painter->restore();
}
@
Not tested though. -
wrote on 19 Nov 2013, 13:07 last edited by
Turned out my first approach there was massive overkill. In the end, it was simple:
@QVariant subclassedModel::data(const QModelIndex& index, int role) const
{
...if (role == Qt::FontRole) { if (condition_on_model_item_to_need_to_be_in_bold_font) { QFont boldFont; boldFont.setBold(true); return boldFont; } }@
1/3