首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在QTreeView中显示图像

问在QTreeView中显示图像
EN

Stack Overflow用户
提问于 2014-02-28 11:11:37
回答 1查看 4.8K关注 0票数 1

我试图在QTreeView中显示一个图像和其他一些数据。为此,我创建了一个QAbstractItemModel。在data方法中,我为列索引0和1返回一些字符串,对于第三个字符串,我希望返回一个图像。但是,没有显示此图像。

当我返回图像作为装饰,它显示很好,但我希望添加点击监听器到图像,将触发一些事件。我还希望在treeview中将我的图像定位到最右边,这似乎需要一个自定义委托。出于这些原因,我为图像创建了一个单独的列。

图像是在构造函数中创建的,如:mEditImage = QImage(":/images/myImage.png");

MyModel

代码语言:javascript
复制
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中显示图像数据方面的任何帮助都是有帮助的。我好像走错了方向。

干杯。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-28 13:16:29

重要的是,如何存储图像。QPixmap对速比绘图很有指导意义。

代码语言:javascript
复制
QVariant MyModel::data(const QModelIndex &index, int role) const
{
 item = itemFromIndex( index ); // Your item implementation
 ...
 case Qt::DisplayRole:
   return item->getText();
 case Qt::DecorationRole:
   return item->getImage();
}

阅读关于角色的Qt文档,这是很好的- http://doc.qt.io/qt-4.8/qt.html#ItemDataRole-enum

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22093510

复制
相关文章

相似问题

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