首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将QTableView列水平调整为委托列的内容,该列在Qt中使用新文本绘制。

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

Stack Overflow用户
提问于 2021-04-02 08:51:48
回答 1查看 150关注 0票数 1

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

代码语言:javascript
运行
复制
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列的大小调整为数据库表列的内容。

现在,我想清除“描述”列的显示文本,并用新的文本和颜色绘制它。对于这个提议,我使用了如下函数QTableView::setItemDelegateForColumn

代码语言:javascript
运行
复制
ui->tableView->setItemDelegateForColumn(2,new PowerColorDelegate(this));

下面是PowerColorDelegate头和源文件内容:

PowerColorDelegate.h

代码语言:javascript
运行
复制
#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

代码语言:javascript
运行
复制
#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 "";
}

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

如何将第三个ui->tableView列(Description)水平调整为已绘制的列的内容?

EN

Stack Overflow用户

回答已采纳

发布于 2021-04-02 12:26:32

根据所需的文本格式为委托实现sizeHint

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66916811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档