[英]How to make a custom QItemDelegate for a particular row in a QTreeView?
如何使自定义QItemDelegate
像上图所示。 这是一个QTreeView
。 我要自定义并添加QItemDelegate
的最后一个元素
目前,我只有绿色的separator
并想在分隔线下方添加一个QCheckBox
。 如何实现这种行为?
void SeparatorItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (index.data(Qt::UserRole + 1).toString() == tr("Unsorted"))
{
QPen pen(Qt::green, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin);
painter->setPen(pen);
painter->drawLine(option.rect.left(), option.rect.center().y(), option.rect.right(), option.rect.center().y());
}
else
{
QItemDelegate::paint(painter, option, index);
}
}
QSize SeparatorItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (index.data(Qt::UserRole + 1).toString() == tr("Unsorted"))
{
return QSize(200, 25);
}
return QItemDelegate::sizeHint(option, index);
}
void SeparatorItemDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
editor->setGeometry(option.rect);
}
问题是:如何将SeparatorLine
和QChekBox
到一个自定义项目中?
在这种情况下,联合的想法是重新粉刷,如下所示:
#include <QApplication>
#include <QItemDelegate>
#include <QPainter>
#include <QStandardItemModel>
#include <QTreeView>
class SeparatorItemDelegate: public QItemDelegate
{
public:
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
QItemDelegate::paint(painter, option, index);
if (index.data(Qt::UserRole + 1).toString() == tr("Unsorted"))
{
QPen pen(Qt::green, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin);
painter->setPen(pen);
QLine line(option.rect.topLeft(), option.rect.topRight());
painter->drawLine(line);
}
}
QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (index.data(Qt::UserRole + 1).toString() == tr("Unsorted"))
return QSize(200, 25);
return QItemDelegate::sizeHint(option, index);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTreeView w;
SeparatorItemDelegate delegate;
w.setItemDelegate(&delegate);
QStandardItemModel model;
for(const QString & root_name: {"Symbols", "Studies", "Drawings", "Unsorted"}){
QStandardItem *root_item = new QStandardItem(root_name);
root_item->setData(root_name);
root_item->setCheckState(Qt::Checked);
model.appendRow(root_item);
for(int i=0; i < 3; i++){
QStandardItem *child_item = new QStandardItem(root_name+QString::number(i));
root_item->appendRow(child_item);
child_item->setCheckState(Qt::Checked);
}
}
w.setModel(&model);
w.expandAll();
w.resize(240, 480);
w.show();
return a.exec();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.