【问题标题】:Using a delegate in a QtableView to show an icon在 QtableView 中使用委托来显示图标
【发布时间】:2018-03-30 11:58:53
【问题描述】:

我想在 QTableview 中实现一个委托以在文本旁边显示一个图标,我应该实现什么类或函数?

【问题讨论】:

标签: c++ qt model-view-controller delegates qtableview


【解决方案1】:

您可以通过setItemDelegate 方法继承QAbstractItemView(例如QColumnViewQTableView 等)的子类QStyledItemDelegate 并设置您自己的委托类。

这是一个简单的例子,它使用这种机制在颜色名称之前用QTableWidget渲染一个颜色块。

main.cpp

#include "QTableWidget"
#include "delegatedemo.hpp"
#include <QApplication>
int
main(int argc, char* argv[])
{
QApplication app(argc, argv);
QTableWidget tableWidget(10, 1);
QStringList headerLabels;
headerLabels << "color";
tableWidget.setHorizontalHeaderLabels(headerLabels);
tableWidget.setItemDelegate(new iconItemDelegate);
tableWidget.show();

return app.exec();
}

delegatedemo.hpp

#ifndef DELEGATEDEMO_HPP
#define DELEGATEDEMO_HPP

#include <QPainter>
#include <QStyledItemDelegate>
class iconItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
iconItemDelegate(QWidget* parent = 0)
    : QStyledItemDelegate(parent)
{
}
void paint(QPainter* painter, const QStyleOptionViewItem& option,
            const QModelIndex& index) const
{
    QColor color(index.data().toString());
    QRect cellRect = option.rect;
    int cH = cellRect.height();
    QRect colorIconArea(QPoint(cH * 0.25, cellRect.y() + cH * 0.25),
                        QSize(cH * 0.5, cH * 0.5));
    if (color.isValid()) {
    painter->fillRect(colorIconArea, QBrush(color));
    painter->drawText(QPoint(cH, cellRect.y() + cH * 0.75),
                        index.data().toString());
    }
}
};
#endif // DELEGATEDEMO_HPP

最终结果是这样的

如果您想显示一个图标,只需让您的自定义委托类中的paint 方法绘制一个图标。

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 2015-03-18
    • 2014-05-13
    • 2019-03-26
    • 1970-01-01
    相关资源
    最近更新 更多