qt - QAbstractTableModel数据返回html代码显示

标签 qt qabstractitemmodel qabstracttablemodel qabstractlistmodel

我希望我的 AbstracttableModel 子类 data() 方法返回 html 即

PreText<b>Text</b>PostText

并且此文本必须像在 html 中一样显示为 int 表: 前文正文后文

我该怎么做?

最佳答案

您可以为将显示 html 的 View 创建一个委托(delegate)。

class HtmlDelegate : public QItemDelegate {
public:
    HtmlDelegate(QObject *parent = 0) : QItemDelegate(parent) {}

    // This function is only called to paint the text
    void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option,
                     const QRect &rect, const QString &text) const
    {
        QTextDocument doc;

        // Since the QTextDocument will do all the rendering, the color,
        // and the font have to be put back inside the doc
        QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
                                  ? QPalette::Normal : QPalette::Disabled;
        if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
            cg = QPalette::Inactive;
        QColor textColor = option.palette.color(cg, QPalette::Text);
        doc.setDefaultStyleSheet(QString("body { color: %1}")
                                 .arg(textColor.name()));
        doc.setDefaultFont(option.font);
        doc.setHtml(text);
        doc.setDocumentMargin(1); // the default is 4 which is too much

        painter->save();
        painter->translate(rect.topLeft());
        doc.drawContents(painter);
        painter->restore();
    }

    // bold and underlined characters take more space
    // so you have to redefine this function as well
    // (if you have a checkbox or an icon in the item, you will have
    // to include their size to the returned value)
    QSize sizeHint(const QStyleOptionViewItem &option,
                   const QModelIndex &index) const
    {
        QTextDocument doc;
        doc.setDefaultFont(option.font);
        doc.setHtml(index.data(Qt::DisplayRole).toString());
        doc.setDocumentMargin(1);
        return doc.size().toSize();
    }
};

然后将它分配给一个 View :

view->setItemDelegateForColumn(0, new HtmlDelegate(view));

关于qt - QAbstractTableModel数据返回html代码显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10073124/

相关文章:

c++ - 使用 SQLite 提高性能

c++ - QTimer: "multiple timeouts"可能吗?

c++ - 无法在 QAbstractItemModel 的 dataChanged 信号槽中获取发送者对象

python - PyQt:自定义属性的 QDataWidgetMapper 映射

c++ - 更改数据库连接后如何更新 QSqlTableModel

码头的 Qt 调整大小事件

html - 具有 HTML 布局格式的 QMessageBox

qt - QObject::connect 与 QAbstractItemModel 的问题

c++ - 使用角色更改 QAbstractTableModel headerData

python - 在 QAbstractItemModel 中不区分大小写排序