C++ (Qt)#ifndef DELEGATE_H#define DELEGATE_H #include <QStyledItemDelegate> class HtmlDelegate : public QStyledItemDelegate{Q_OBJECT public:HtmlDelegate(QObject *parent = 0); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;}; #endif
C++ (Qt)#include "delegate.h" #include <QtWidgets> HtmlDelegate::HtmlDelegate(QObject *parent) : QStyledItemDelegate(parent){} void HtmlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {QStyleOptionViewItem opt = option;initStyleOption(&opt, index); painter->save(); QTextDocument doc(opt.text); doc.setHtml(opt.text); opt.text = "";opt.widget->style()->drawControl(QStyle::CE_ItemViewItem, &option, painter); painter->translate(opt.rect.left(), opt.rect.top());QRect clip(0, 0, opt.rect.width(), opt.rect.height());doc.drawContents(painter, clip); painter->restore();}
C++ (Qt)#include "delegate.h"#include <QApplication>#include <QtWidgets> int main(int argc, char *argv[]){QApplication app(argc, argv); QStringListModel model;QTableView tableView; QStringList lst;lst << "<b>Bold text.</b> Custom text." << "It's <font color=red><b>red</b></font> text. <i>Italic</i>"; model.setStringList(lst);tableView.setModel(&model); HtmlDelegate delegate;tableView.setItemDelegate(&delegate);tableView.setEditTriggers(QAbstractItemView::NoEditTriggers); tableView.setWindowTitle("Html delegate");tableView.show();tableView.resizeColumnsToContents(); return app.exec();}
C++ (Qt)#ifndef DELEGATE_H#define DELEGATE_H #include <QStyledItemDelegate> class HtmlDelegate : public QStyledItemDelegate{ Q_OBJECT public:HtmlDelegate(QObject *parent = 0); QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; void setEditorData(QWidget* editor, const QModelIndex& index) const;}; #endif
C++ (Qt)#include "delegate.h" #include <QtWidgets> HtmlDelegate::HtmlDelegate(QObject *parent) : QStyledItemDelegate(parent){} QWidget* HtmlDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const{QLabel* label = new QLabel(parent); return label;} void HtmlDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const{QString value = index.model()->data(index, Qt::DisplayRole).toString(); QLabel* label = static_cast<QLabel*>(editor); label->setText(value);}
C++ (Qt)int main(int argc, char *argv[]){QApplication app(argc, argv); QStringListModel model;QTableView tableView; QStringList lst; lst << "<b>First</b> html text" << "Second html <i>text</i>"; model.setStringList(lst);tableView.setModel(&model); HtmlDelegate delegate;tableView.setItemDelegate(&delegate);tableView.setEditTriggers(QAbstractItemView::NoEditTriggers); tableView.setWindowTitle("Html delegate");tableView.show();tableView.resizeColumnsToContents();for(int i=0; i<lst.count(); ++i) {tableView.openPersistentEditor(model.index(i)); // view delegate all time} return app.exec();}