如何删除QTreeView缩进 [英] How to remove QTreeView indentation

查看:883
本文介绍了如何删除QTreeView缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每个嵌套级别的左侧增加一个QTreeView 凹痕.我尝试设置QTreeView::setIndentation(0).它会按照我的意愿删除压痕,但是也会隐藏树形箭头.

I want to have a QTreeView without an indentation on the left side increasing at each nesting level. I tried setting QTreeView::setIndentation(0). It removes the indentations just as I want, however it also hides the tree arrows.

  • 带有缩进✗
  • 带有箭头✔

  • 没有缩进✔
  • 没有箭头✗

  • 没有缩进✔
  • 带有箭头✔

那么如何获得第三个示例中显示的结果?有什么标准方法可以执行,还是必须重新实现QTreeView::paintEvent()QTreeView::drawBranches()等?

So how can I achieve the result shown in the third example? Is there any standard way of doing it, or I will have to reimplement the QTreeView::paintEvent(), QTreeView::drawBranches(), etc.?

推荐答案

为解决此问题,我使用了一个委托来翻译项目的绘制并绘制箭头.

To solve the problem I used a delegate to translate the paint of the items, and paint the arrows.

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

这篇关于如何删除QTreeView缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆