c++qtqtreewidgetqscrollbar

QTreeWidget with non-native scroll bar when background changed


I need a QTreeWidget with transparent background so it has the same color as the native light-gray window background. This works fine by setting the background to transparent.

The problem is that if I do this, the scroll becomes non-native looking. The default background of QTreeWidget is "white" and if I don't change it, the scroll bar does look native. However, if I change the background to "transparent", the scrollbar looses its native appearance.

To demonstrate this, I put two QTreeWidgets next to each other, one with the default white background showing the native scroll bar and one with the background changed to transparent, showing a non-native scroll bar: screenshot

enter image description here

Here is the code:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QHBoxLayout* layout = new QHBoxLayout(this);
    ui->centralWidget->setLayout(layout);

    QTreeWidget* tree1 = new QTreeWidget();
    QTreeWidget* tree2 = new QTreeWidget();
    layout->addWidget(tree1);
    layout->addWidget(tree2);

    // add ten items to each tree widget
    for(int i=0; i<10; i++){
        QString item_text = "item " + QString::number(i);

        QTreeWidgetItem* item1 = new QTreeWidgetItem();
        item1->setText(0, item_text);
        tree1->addTopLevelItem(item1);

        QTreeWidgetItem* item2 = new QTreeWidgetItem();
        item2->setText(0, item_text);
        tree2->addTopLevelItem(item2);
    }

    // change the background color of tree2 to the window color
    //   this leads to a non native scroll bar for tree2
    tree2->setStyleSheet("background-color: transparent;");
}

How can I have the transparent background an still keep the native scroll bar?


Solution

  • I finally found the solution. I need to restrict the definition of the background-color to the QTreeWidget:

    tree2->setStyleSheet("QTreeWidget {background-color: transparent;}");