0
点赞
收藏
分享

微信扫一扫

Qt | QListWidgetItem返回错误的背景颜色(始终返回颜色值为0)问题解决


Qt | QListWidgetItem返回错误的背景颜色(始终返回颜色值为0)问题解决

使用场景:程序使用QListWidget显示一个列表,这个列表具有点击选择和再次点击取消选择的功能,点击之后需要更换背景色以表示被选中,由于软件有主题效果,所以打算让背景色自动选择背景颜色取反显示,让软件去自适应。

问题描述:使用​​ui->listWidget->item(index.row())->background()​​获取到的brush始终为0。

问题原因:默认情况下QListWidgetItem的背景QBrush是为空的,所以默认颜色为ListWidget的背景颜色,因此不会使用绘画,即不绘制背景颜色,所以获取到的brush转成qcolor后的颜色值始终为0。

前景也是同样的情况,而前景使用视图调色板的文本颜色作为前景色。

因此,如果您想要获得背景颜色和文本颜色,如果QBrush为空,那么可以获取视图的调色板的颜色。

我的代码修改前:

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())));
});

修改后:

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…


举报

相关推荐

0 条评论