Как удалить отступ QTreeView - PullRequest
1 голос
/ 03 мая 2019

Я хочу, чтобы QTreeView без отступ с левой стороны увеличивался на каждом уровне вложенности.Я попытался установить QTreeView::setIndentation(0).Он удаляет отступы так, как я хочу, но также скрывает стрелки дерева.


Поведение по умолчанию:

  • С отступами ✗
  • Со стрелками ✔

Default behavior


После setIndentation(0):

  • Без отступов 10
  • Без стрелок ✗

After setIndentation(0)


Желаемое поведение:

  • Без отступов ✔
  • Со стрелками ✔

Desired behavior


Итак, как мне достичь результата, показанного в третьем примере?Есть ли какой-нибудь стандартный способ сделать это, или мне придется переопределить QTreeView::paintEvent(), QTreeView::drawBranches() и т. Д .?

1 Ответ

2 голосов
/ 04 мая 2019

Для решения проблемы я использовал делегата, чтобы перевести краски предметов и нарисовать стрелки.

#include <QtWidgets>

class BranchDelegate: public QStyledItemDelegate
{
public:
    using QStyledItemDelegate::QStyledItemDelegate;
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override{
        QStyleOptionViewItem opt(option);
        if(index.column() == 0)
            opt.rect.adjust(opt.rect.height(), 0, 0, 0);
        QStyledItemDelegate::paint(painter, opt, index);
        if(index.column() == 0){
            QStyleOptionViewItem branch;
            branch.rect = QRect(0, opt.rect.y(), opt.rect.height(), opt.rect.height());
            branch.state = option.state;
            const QWidget *widget = option.widget;
            QStyle *style = widget ? widget->style() : QApplication::style();
            style->drawPrimitive(QStyle::PE_IndicatorBranch, &branch, painter, widget);
        }
    }
};

class TreeView: public QTreeView
{
public:
    TreeView(QWidget *parent=nullptr):QTreeView(parent)
    {
        BranchDelegate *delegate = new BranchDelegate(this);
        setItemDelegate(delegate);
        setIndentation(0);
    }
protected:
    void mousePressEvent(QMouseEvent *event) override{
        QModelIndex index = indexAt(event->pos());
        bool last_state = isExpanded(index);
        QTreeView::mousePressEvent(event);
        if(index.isValid() && last_state == isExpanded(index))
            setExpanded(index, !last_state);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TreeView w;
    QFileSystemModel model;
    model.setRootPath(QDir::rootPath());
    w.setModel(&model);
    w.setRootIndex(model.index(QDir::homePath()));
    /*for (int i = 1; i< model.columnCount() ; ++i) {
        w.hideColumn(i);
    }*/
    w.expandAll();
    w.resize(640, 480);
    w.show();
    return a.exec();
}
...