我在QListView
. 我目前有一个QListView
显示我的自定义模型,称为PlayQueue
基于QAbstractListModel
.
这适用于简单的文本,但现在我想为每个元素显示一个自定义小部件。所以我将 a 子类QStyledItemDelegate
化来实现这样的paint
方法:
void QueueableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
if (option.state & QStyle::State_Selected)
painter->fillRect(option.rect, option.palette.highlight());
QWidget *widget = new QPushButton("bonjour");
widget->render(painter);
}
选择背景已正确呈现,但未显示任何小部件。我尝试使用QPainter
Qt 示例中的简单命令,效果很好:
void QueueableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
if (option.state & QStyle::State_Selected)
painter->fillRect(option.rect, option.palette.highlight());
if (option.state & QStyle::State_Selected)
painter->setPen(option.palette.highlightedText().color());
painter->setFont(QFont("Arial", 10));
painter->drawText(option.rect, Qt::AlignCenter, "Custom drawing");
}
所以我尝试了一些更改,例如:
- 更改
QStyledItemDelegate
为QItemDelegate
- 添加
painter->save()
和painter->restore()
围绕渲染 - 将小部件几何设置为可用大小
但是我现在有点卡住了,我在互联网上搜索了一段时间,但找不到任何我想要的示例,他们都在谈论编辑小部件(这更容易)或自定义绘制控件(预定义的,如进度条)。但在这里我真的需要一个我创建的自定义小部件,其中包含一些布局、标签和像素图。谢谢你的帮助!
我在 Ubuntu 11.04 上为 GCC 使用 Qt 4.7.3。