c++ - 如何为 QTreeView 中的特定行制作自定义 QItemDelegate?
问题描述
如何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);
}
问题是:
如何将 aSeparatorLine
和 a结合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();
}
推荐阅读
- r - R包Future - 为什么与远程工作者的循环会挂起本地R会话
- angularjs - AngularJS:Swiper.js 不显示背景图像
- javascript - 如何使用 Django 后端保护 AJAX 调用?
- google-apps-script - 用于发送电子邮件的 Google 表格脚本
- python - 从熊猫的嵌套字典列中提取值
- button - 使用内部文本单击按钮
- javascript - 要求选中表格上的所有框
- python - 在 timeit.timeit() 中使用较大数字的时间更少?
- reactjs - 如何在请求中自动发送 cookie 内容?
- swift - 无法快速访问闭包内的变量