gpt4 book ai didi

c++ - 如何为 QTreeView 中的特定行创建自定义 QItemDelegate?

转载 作者:行者123 更新时间:2023-11-28 01:28:18 25 4
gpt4 key购买 nike

如何制作一个自定义的 QItemDelegate 就像所附的图片一样。这是一个 QTreeView。我要自定义的最后一个元素并添加一个 QItemDelegate enter image description here

现在我只有绿色的 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);
}

问题是:如何将 SeparatorLineQChekBox 合并到一个自定义项中?

最佳答案

在这种情况下,union 的想法是重绘,如下所示:

#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();
}

enter image description here

关于c++ - 如何为 QTreeView 中的特定行创建自定义 QItemDelegate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52813468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com