Qt | QListWidgetItem returns the wrong background color (always returns a color value of 0) problem solving

Qt | QListWidgetItem returns the wrong background color (always returns a color value of 0) problem solving


Usage scenario: The program uses QListWidget to display a list. This list has the function of clicking to select and clicking again to cancel the selection. After clicking, the background color needs to be changed to indicate that it is selected. Since the software has a theme effect, it is planned to let the background color automatically select the background color. Anti-display, let the software adapt itself.

Description of the problem: The ui->listWidget->item(index.row())->background()obtained brush is always 0.

Cause of the problem: By default, the background QBrush of QListWidgetItem is empty, so the default color is the background color of ListWidget, so painting will not be used, that is, the background color will not be drawn, so the color value after the obtained brush is converted into qcolor is always 0.

The same is the case for the foreground, which uses the text color of the view palette as the foreground color.

So if you want to get the background color and text color, if the QBrush is empty, you can get the colors of the view's palette.

My code before modification:

    connect(ui->listWidget, &QListWidget::clicked, this, [=](const QModelIndex& index){
    
    

        QBrush brush = ui->listWidget->item(index.row())->background();
        QColor color(brush.color());
        ui->listWidget->item(index.row())->setBackground(QBrush(QColor(255 - color.red(), 255 - color.green(), 255 - color.blue())));
    });

After modification:

    connect(ui->listWidget, &QListWidget::clicked, this, [=](const QModelIndex& index){
    
    
        QBrush brush = ui->listWidget->item(index.row())->background();
        if(brush.style() == Qt::NoBrush)
        {
    
    
            brush = ui->listWidget->palette().window(); // 或ui->listWidget->palette().background()
            qDebug() << "no brush";
        }
        QColor color(brush.color());
        ui->listWidget->item(index.row())->setBackground(QBrush(QColor(255 - color.red(), 255 - color.green(), 255 - color.blue())));
    });

ends…

Guess you like

Origin blog.csdn.net/qq153471503/article/details/128068926