Important: Please read the Qt Code of Conduct -

[Solved] QListview - alter font of one line dynamically

  • 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?

  • Moderators

    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));
    QStyleOptionViewItem opt = option;

    this->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
        painter->drawText( option.rect, text );

    Not tested though.

  • 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;
            return boldFont;

Log in to reply