如何在QTreeWidget中替换空白空间颜色?

时间:2019-04-15 14:38:41

标签: qt colors qtreewidget alternate alternating

如果我输入此代码

myTree->setAlternatingRowColors(true);
myTree->setStyleSheet("QTreeWidget{alternate-background-color: red;background: green;}");

行的颜色是交错的。但是,如果QTreeWidget未满,则会有一个绿色的空白空间。最后一行为绿色时,是否可以用红色刷这个空间?

P.S。

#include <QApplication>
#include <QWidget>
#include <QTreeWidget>

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

    QWidget *mainWidget = new QWidget();
    mainWidget->resize(200,100);
    QTreeWidget *myTree = new QTreeWidget(mainWidget);
    myTree->resize(200,100);

    QTreeWidgetItem *newTreeItem;
    newTreeItem = new QTreeWidgetItem(myTree);
    newTreeItem->setText(0,"leaf_01");
    newTreeItem = new QTreeWidgetItem(myTree);
    newTreeItem->setText(0,"node_02");
    newTreeItem = new QTreeWidgetItem(newTreeItem);
    newTreeItem->setText(0,"leaf_03");

    myTree->setAlternatingRowColors(true);
    myTree->setStyleSheet("QTreeWidget{alternate-background-color: red; background: green;}");

    mainWidget->show();

    return a.exec();
}

enter image description here

1 个答案:

答案 0 :(得分:0)

我试图重新定义QTreeWidget的drawRow。

效果很好,但这是一个好习惯吗?

void myTreeWidget::drawRow(QPainter *p, const QStyleOptionViewItem &opt, const QModelIndex &idx) const
{   
    if(itemFromIndex(idx)) {
        if(!itemBelow(itemFromIndex(idx))) {

            int counter = 0;
            QTreeWidgetItem *currentItem = topLevelItem(0);
            if(currentItem) {
                while(itemBelow(currentItem)) {
                    currentItem=itemBelow(currentItem);
                    counter = counter + 1;
                }
            }

            if(counter % 2) {
                p->setBrush(oddColor);
            } else {                
                p->setBrush(evenColor);
            }

            QRect itemRect = visualRect(idx);
            QRect emptySpace = this->rect();
            emptySpace.setTop(itemRect.y()+itemRect.height());
            p->setPen(Qt::transparent);
            p->drawRect(emptySpace);
        }
    }

    QTreeWidget::drawRow(p, opt, idx);
}