在 QTreeView 中的文本之前显示图标 [英] Display an icon before text in a QTreeView

查看:42
本文介绍了在 QTreeView 中的文本之前显示图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Qt 4.8.6 中使用 QtRuby 并尝试创建一个树视图,其中每个项目在树控件和名称之间都有一个自定义图标.最终结果应该是这样的:
           

I'm using QtRuby with Qt 4.8.6 and trying to create a tree view where each item has a custom icon between the tree controls and the name. The end result should be like this:
                     

我正在为图标应该去的位置分配空间,但我没有看到任何图标.我该怎么做才能让他们出现?
           

I am getting space allocated for where the icon should go, but I'm not seeing any icons. What do I have to do to get them to show up?
                     

这是我的代码(稍微简化以删除无数据边缘情况):

Here's my code (simplified slightly to remove the no-data edge cases):

class MyModel < Qt::AbstractItemModel
  # ...
  def data(index, role)
    case role
      when Qt::DisplayRole
        case index.column
          when 0; Qt::Variant.new(index.internalPointer.displayName)
          when 1; Qt::Variant.new(index.internalPointer.displayType)
        end
      when Qt::DecorationRole
        if index.column==0 then
          # Just testing to show a static icon for all items
          Qt::Pixmap.new(':/resources/images/Objects-Scene-Normal.png')
        end
    end
  end
end

@mytreeview.model = MyModel.new

如果您想检查 Qt Designer .ui 文件(以防树视图需要设置我没有的属性),它可以是 见这里.

If you want to inspect the Qt Designer .ui file (in case the tree view needs to have a property set that I have not) it can be seen here.

推荐答案

显然 QPixmap 需要包裹在 QVariant 中才能正常工作.这是在 QtRuby 中使用 Qt::Variant.fromValue():

Apparently the QPixmap needs to be wrapped in a QVariant to work properly. This is done in QtRuby by using Qt::Variant.fromValue():

when Qt::DecorationRole
  if index.column==0 then
    Qt::Variant.fromValue( Qt::Pixmap.new(':/path/to/resource') )

感谢#qt irc.freenode.net 上的 andrepeppe 对此的帮助.

这篇关于在 QTreeView 中的文本之前显示图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆