使用 QListView 和 QStandardItemModel,是否可以在 ListView 中显示图标而不显示相关文本? QStandardItem 定义如下:
QStandardItem ( const QIcon & icon, const QString & text )
所以它似乎需要某种文本字符串——我只希望显示图标。如果我使用以下代码,我会按要求获得图标,但我也会在它们下面得到一个空白文本元素。我不想要这个。
ImageListView->setViewMode( QListView::IconMode );
{
QStandardItemModel *iStandardModel = new QStandardItemModel(this);
QStandardItem* item1 = new QStandardItem(QIcon("images/shield-280x280.png"),"");
QStandardItem* item2 = new QStandardItem(QIcon("images/shield-280x280.png"),"");
iStandardModel->appendRow(item1);
iStandardModel->appendRow(item2);
ImageListView->setIconSize(QSize(100,100));
ImageListView->setUniformItemSizes(true);
ImageListView->setDragDropMode(QAbstractItemView::DropOnly);
ImageListView->setModel(iStandardModel);
}
如果我去构建自定义模型的麻烦,我可以解决这个问题吗?
最佳答案
为了扩展已接受的答案,这里是最简单的委托(delegate),它可以选择隐藏项目的文本(显示角色),但在其他方面就像默认委托(delegate)一样。这适用于任何 QAbstractItemView
子类(和 QComboBox
)和任何 QAbstractItemModel
子类。如果人们宁愿为其他 View (或任何原因)保持显示角色非空,这是一个更好的解决方案。
class ItemDelegate : public QStyledItemDelegate
{
public:
using QStyledItemDelegate::QStyledItemDelegate;
// simple public member to toggle the display role (create getter/setter if you prefer)
bool displayRoleEnabled = false;
protected:
void initStyleOption(QStyleOptionViewItem *o, const QModelIndex &idx) const override
{
QStyledItemDelegate::initStyleOption(o, idx);
// to hide the display role all we need to do is remove the HasDisplay feature
if (!displayRoleEnabled)
o->features &= ~QStyleOptionViewItem::HasDisplay;
}
};
关于c++ - 有没有办法在没有文本的情况下在 QListView 中显示图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2597534/