如何在QTableview的单元格中呈现用户定义的小部件(不使用qml)

时间:2016-03-23 13:47:17

标签: c++ qt qabstracttablemodel qitemdelegate

这些天我遇到了关于qt的问题。 我想在Qt应用程序中使用QTableview显示批处理数据(不是qml gridview,因为我的应用程序使用小部件)。每个数据项包括图像和图像名称。我需要让图像显示在qlabel上,并将其名称显示在另一个qlabel上。这两个小部件应该在我自己定义的框架上显示。然后我将让每个QTableView单元格中显示用户定义的框架。

从BigBourin(也问类似的问题),我知道我应该实现一个自定义的委托,并重新实现画家功能,就像这样:

void PackageListItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{

// here we have active painter provided by caller

// by the way - we can't use painter->save() and painter->restore()
// methods cause we have to call painter->end() method before painting
// the QWidget, and painter->end() method deletes
// the saved parameters of painter

// we have to save paint device of the provided painter to restore the painter
// after drawing QWidget
QPaintDevice* original_pdev_ptr = painter->device();

// example of simple drawing (selection) before widget
if (option.state & QStyle::State_Selected)
    painter->fillRect(option.rect, option.palette.highlight());

// creating local QWidget (that's why i think it should be fasted, cause we 
// don't touch the heap and don't deal with a QWidget except painting)
PackageListItemWidget item_widget;

// Setting some parameters for widget for example
    // spec. params
item_widget.SetPackageName(index.data(Qt::DisplayRole).toString());     
    // geometry
item_widget.setGeometry(option.rect);

// here we have to finish the painting of provided painter, cause
//     1) QWidget::render(QPainter *,...) doesn't work with provided external painter 
//          and we have to use QWidget::render(QPaintDevice *,...)
//          which creates its own painter
//     2) two painters can't work with the same QPaintDevice at the same time
painter->end(); 

// rendering of QWidget itself
item_widget.render(painter->device(), QPoint(option.rect.x(), option.rect.y()), QRegion(0, 0, option.rect.width(), option.rect.height()), QWidget::RenderFlag::DrawChildren);   

// starting (in fact just continuing) painting with external painter, provided
// by caller
painter->begin(original_pdev_ptr);  

// example of simple painting after widget
painter->drawEllipse(0,0, 10,10);   
};

我的问题是item_widget.SetPackageName(index.data(Qt :: DisplayRole).toString());

数据来自哪里?数据可以是用户定义的数据类吗?

0 个答案:

没有答案