【发布时间】:2016-02-24 03:36:52
【问题描述】:
我正在尝试在QTreeView 中显示图像以及其他一些数据。为此,我创建了一个QAbstractItemModel。在data 方法中,我为列索引0 和1 返回一些字符串,而对于第三个我希望返回图像。但是,此图像未显示。
当我将图像作为装饰返回时,它显示正常,但我希望将点击侦听器添加到将触发某些事件的图像中。我还希望将我的图像定位在树视图的最右侧,这似乎需要一个自定义委托。由于这些原因,我为图像创建了一个单独的列。
像这样在构造函数中创建图像:mEditImage = QImage(":/images/myImage.png");
我的模特
QVariant MyModel::data(const QModelIndex &index, int role) const {
if (!index.isValid()) {
return QVariant();
}
if(role == Qt::FontRole) {
return fontData(index);
}
if(role == Qt::ForegroundRole) {
return foreGroundData(index);
}
MyModelItem *item = getItem(index);
/*
* Use decoration to display image. Probably needs a
* custom delegate to be able to position the image correctly.
* (http://www.qtcentre.org/threads/49639-decoration-position-and-alignment)
* (https://qt-project.org/forums/viewthread/24493)
*
* Will use extra column for now instead. Might help with click
* listeners as well.
*
* if(role == Qt::DecorationRole && item->parent() != mRootItem) {
return index.column() == 1 ? mEditImage : QVariant();
}*/
if(role == Qt::SizeHintRole) {
return mEditImage.size();
}
if (role == Qt::DisplayRole) {
QString id = QString::number(item->id());
QString name = item->name();
if(item->parent() != mRootItem && index.column() == 2) {
return mEditImage;
}
if(item->parent() == mRootItem){
return index.column() == 0 ? name : "";
} else {
return index.column() == 0 ? id : name;
}
} else if(role == Qt::BackgroundRole) {
return QVariant();
}
我看过这里:
http://www.qtcentre.org/threads/29550-How-do-I-display-a-picture-on-a-QTableView-cell
How to set an image for a row?
我尝试将图像更改为QPixmap 和QIcon,并尝试将其嵌入QLabel(无法转换为QVariant),但运气不佳。将图像更改为 QString 会显示字符串,因此行/列逻辑看起来不错。删除SizeHintRole 逻辑也没有任何区别。
了解如何在QTreeView 中显示图像数据的任何帮助都会有所帮助。我似乎从错误的方向前进。
干杯。
【问题讨论】: