如何在Qtreewidget中删除虚线分支

时间:2019-02-27 05:38:43

标签: c++ qt qtreeview qtstylesheets qtreewidget

我希望删除Qtreewidget(QT C ++)中的虚线分支。但是问题是我是否使用

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

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

原始树小部件:

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

所需的treeWidget:

- ABCD
     EFGH
     IJKL
+ MNOP

那么,我该怎么办?

1 个答案:

答案 0 :(得分:1)

可能的解决方案是使用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();
}