将 QTableView 列水平调整为项目委托列的内容,该列在 Qt 中用新文本绘制

Resizing a QTableView column horizontally to the content of an item delegated column which is painted with a new text in Qt

我想在 QTableView 中显示我的数据库标签内容。我使用以下代码来做到这一点:

QSqlDatabase test = QSqlDatabase::addDatabase("QMYSQL");
test.setDatabaseName("dbText");
test.setHostName("localhost");
test.setUserName("***");
test.setPassword("***");

if (!test.open())
qDebug()<<"ERROR ";

QSqlTableModel *model = new QSqlTableModel(this,test);
model->setTable("textTable");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();

ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);

ui->tableView->setModel(model);
ui->tableView->show();

如下图所示,ui->tableView 列的大小已调整为数据库 table 列的内容。

现在,我想清除 Description 列的显示文本,并用新的文本和颜色对其进行绘制。对于这个提议,我使用函数 QTableView::setItemDelegateForColumn 如下:

ui->tableView->setItemDelegateForColumn(2,new PowerColorDelegate(this));

这里是 PowerColorDelegate 头文件和源文件内容:

PowerColorDelegate.h

#include <QStyledItemDelegate>

class PowerColorDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    PowerColorDelegate(QObject *parent = 0);

protected:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
    QString displayText(const QVariant &value, const QLocale &locale) const;
};

PowerColorDelegate.cpp

#include <QApplication>
#include <QPainter>
#include "powercolordelegate.h"

PowerColorDelegate::PowerColorDelegate(QObject *parent) : QStyledItemDelegate(parent)
{
}

void PowerColorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);

    if(!index.isValid())
    {
        QStyledItemDelegate::paint(painter, option, index);
        return;
    }

    // Position our pixmap
    const int x = option.rect.left();
    const int y = option.rect.top();

    QString newColor = "#fcaf9e";
    QString newText = "This is my new text which I want to paint!";

    painter->fillRect(option.rect, newColor);
    painter->drawText(QRect(x, y, 80, 20), newText);

    QStyledItemDelegate::paint(painter, opt, index);
}

QString PowerColorDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
    return "";
}

ui->tableView上使用PowerColorDelegate的结果如图所示:

如何调整第三个 ui->tableView 列 (Description) 的大小以适应绘制列的内容?

根据要求的文本格式为您的委托实施 sizeHint