问题
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
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.
回答1:
I think the image cannot be found with the path specified. Verify it with QFileInfo::exists().
回答2:
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:
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.
来源:https://stackoverflow.com/questions/26267294/display-an-icon-before-text-in-a-qtreeview