How to make a fast QTableView with HTML-formatted and clickable cells?

后端 未结 4 1119

I\'m making a dictionary program that displays word definitions in a 3-column QTableView subclass, as user types them, taking data from a QAbstractTableModel<

4条回答
  •  悲&欢浪女
    2021-01-31 01:13

    I use a slighted improved solution based on Xilexio code. There is 3 fundamental differences:

    • Vertical alignment so if you put the text in a cell higher than the text it will be center aligned and not top aligned.
    • The text will be right shifted if the cell contains an icon so the icon will not be displayed above the text.
    • The widget style to highlighted cells will be followed, so you select this cell, the colors will behave similar to other cells without the delegate.

    Here is my code of the paint() function (the rest of the code remains the same).

    QStyleOptionViewItemV4 options = option;
    initStyleOption(&options, index);
    
    painter->save();
    
    QTextDocument doc;
    doc.setHtml(options.text);
    
    options.text = "";
    options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);
    
    QSize iconSize = options.icon.actualSize(options.rect.size);
    // right shit the icon
    painter->translate(options.rect.left() + iconSize.width(), options.rect.top());
    QRect clip(0, 0, options.rect.width() + iconSize.width(), options.rect.height());
    
    painter->setClipRect(clip);
    QAbstractTextDocumentLayout::PaintContext ctx;
    
    // Adjust color palette if the cell is selected
    if (option.state & QStyle::State_Selected)
        ctx.palette.setColor(QPalette::Text, option.palette.color(QPalette::Active, QPalette::HighlightedText));
    ctx.clip = clip;
    
    // Vertical Center alignment instead of the default top alignment
    painter->translate(0, 0.5*(options.rect.height() - doc.size().height()));
    
    doc.documentLayout()->draw(painter, ctx);
    painter->restore();
    

提交回复
热议问题