Display an icon before text in a QTreeView

2019-05-15 11:12发布

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:
                      tree view with icons before each item

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?
                      tree view with 2 columns, but no icons

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

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.

3条回答
唯我独甜
2楼-- · 2019-05-15 11:16

use QTreeWidget insted of QTreeView. then create a new form class (YourTreeWidgetItem) for your new items, every thing you like, then do this:

YourTreeWidgetItem* wItem = new YourTreeWidgetItem;
treeWidget->setItemWidget(wItem);

but it is c++ Qt code

查看更多
唯我独甜
3楼-- · 2019-05-15 11:25

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') )

Credit to andre and peppe on #qt irc.freenode.net for helping with this.

查看更多
祖国的老花朵
4楼-- · 2019-05-15 11:40

I think the image cannot be found with the path specified. Verify it with QFileInfo::exists().

查看更多
登录 后发表回答