如何删除Qtreewidget中的虚线分支

How to remove dotted branches in Qtreewidget

我想删除 Qtreewidget (QT C++) 中的虚线分支。但问题是如果我使用

setStyleSheet(QString("QTreeView::branch{background:palette(base)}"));

用于展开和折叠的 + 和 - 符号也消失了。

原始树小部件:

- ABCD
|
|--- EFGH
|--- IJKL
+ MNOP

所需的 treeWidget:

- ABCD
     EFGH
     IJKL
+ MNOP

那么,我该怎么做呢?

一个可能的解决方案是使用 QProxyStyle:

#include <QtWidgets>

class BranchStyle: public QProxyStyle
{
public:
    using QProxyStyle::QProxyStyle;
    void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p, const QWidget *w) const override{
        if(pe == PE_IndicatorBranch) {
            static const int decoration_size = 9;
            int mid_h = opt->rect.x() + opt->rect.width() / 2;
            int mid_v = opt->rect.y() + opt->rect.height() / 2;
            int bef_h = mid_h;
            int bef_v = mid_v;
            int aft_h = mid_h;
            int aft_v = mid_v;
            if (opt->state & State_Children) {
                int delta = decoration_size / 2;
                bef_h -= delta;
                bef_v -= delta;
                aft_h += delta;
                aft_v += delta;
                p->drawLine(bef_h + 2, bef_v + 4, bef_h + 6, bef_v + 4);
                if (!(opt->state & State_Open))
                    p->drawLine(bef_h + 4, bef_v + 2, bef_h + 4, bef_v + 6);
                QPen oldPen = p->pen();
                p->setPen(opt->palette.dark().color());
                p->drawRect(bef_h, bef_v, decoration_size - 1, decoration_size - 1);
                p->setPen(oldPen);
            }
            return;
        }
        QProxyStyle::drawPrimitive(pe, opt, p, w);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QTreeWidget w;
    w.setStyle(new BranchStyle(w.style()));

    QTreeWidgetItem *item1 = new QTreeWidgetItem({"ABCD"});
    w.addTopLevelItem(item1);
    QTreeWidgetItem *item11 = new QTreeWidgetItem({"EFGH"});
    item1->addChild(item11);
    QTreeWidgetItem *item12 = new QTreeWidgetItem({"IJKL"});
    item1->addChild(item12);
    QTreeWidgetItem *item2 = new QTreeWidgetItem({"MNOP"});
    w.addTopLevelItem(item2);
    QTreeWidgetItem *item21 = new QTreeWidgetItem({"RSTU"});
    item2->addChild(item21);
    QTreeWidgetItem *item22 = new QTreeWidgetItem({"VWXY"});
    item2->addChild(item22);
    w.expandAll();
    w.show();
    return a.exec();
}