使用QStyledItemDelegate代理手动绘制文字
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStyledItemDelegate>
class QTableView;
class QStandardItemModel;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
QTableView *mTable = nullptr;
QStandardItemModel *mModel = nullptr;
};
class MultiLineDelegate: public QStyledItemDelegate
{
Q_OBJECT
public:
MultiLineDelegate(QObject *parent = nullptr): QStyledItemDelegate(parent) { }
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include <QApplication>
#include <QTableView>
#include <QStandardItemModel>
#include <QHeaderView>
#include <QPainter>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
mTable = new QTableView(this);
mModel = new QStandardItemModel(this);
mTable->setModel(mModel);
this->setCentralWidget(mTable);
mTable->setItemDelegateForColumn(4, new MultiLineDelegate);//可设置某行、某列或全部
QStringList headers;
headers << "Name" << "Age" << "Gender" << "Email" << "Remark";
mModel->setHorizontalHeaderLabels(headers);
mTable->verticalHeader()->setVisible(false);
mTable->horizontalHeader()->setStretchLastSection(true);
mModel->setItem(0, 0, new QStandardItem("1"));
mModel->setItem(0, 1, new QStandardItem("2"));
mModel->setItem(0, 2, new QStandardItem("3"));
mModel->setItem(0, 3,new QStandardItem("4"));
mModel->setItem(0, 4,new QStandardItem(QStringLiteral("白日依山尽,黄河入海流。")));
resize(800, 600);
}
MainWindow::~MainWindow()
{
}
void MultiLineDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (!index.isValid()) {
return;
}
QStyleOptionViewItemV4 opt = option;
initStyleOption(&opt,index);
QString oldtext = opt.text;
opt.text = "";
const QWidget *widget = opt.widget;
QStyle *style = widget ? widget->style() : QApplication::style();
QRect txtrect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);
// 去除选择时的虚线框
if (opt.state & QStyle::State_HasFocus) {
opt.state = opt.state ^ QStyle::State_HasFocus;
}
// 选中文字颜色不变
// opt.palette.setColor(QPalette::HighlightedText, index.data(Qt::ForegroundRole).value<QColor>());
style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
QRect boundingRect;
painter->save();
painter->setPen(opt.palette.color(QPalette::Text));
if (opt.state & QStyle::State_Selected) {
painter->setPen(opt.palette.color(QPalette::HighlightedText));
}
painter->drawText(txtrect, Qt::TextWordWrap|Qt::AlignVCenter, oldtext, &boundingRect);
painter->restore();
}
设置代理前:
设置代理后:
评论区