qtqtableviewqsqltablemodelqitemdelegateqstyleditemdelegate

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


I want to show my database tabel content in a QTableView. I use the following codes to do that:

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();

As it is depicted in the following picture, ui->tableView columns are resized to the content of the database table columns.

enter image description here

Now, I want to clear the display text of Description column and paint it with new text and color. For this propose, I have used the function QTableView::setItemDelegateForColumn as follow:

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

And here are PowerColorDelegate header and source file content:

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 "";
}

The result of using PowerColorDelegate on ui->tableView is shown in this picture:

****

How can I resize the third ui->tableView column (Description) horizontally to the content of the painted column?


Solution

  • Implement sizeHint for your delegate according to required text format