gpt4 book ai didi

Qt如何更改特定QComboBox项目的突出显示颜色

转载 作者:行者123 更新时间:2023-12-03 16:04:00 29 4
gpt4 key购买 nike

我正在尝试使 QComboBox 的突出显示透明。此 QComboBox 的颜色也会根据所选索引而变化。到目前为止,这是我最好的解决方案:

switch(comboBox->currentIndex())
{
case 0:
comboBox->setStyleSheet("QWidget {color:black}");
break;

case 1:
comboBox->setStyleSheet("QWidget {background-color:red; color:white;}");
break;

case 2:
comboBox->setStyleSheet("QWidget {background-color:green; color:white;}");
break;
}


comboBox->setItemData(0, QColor(Qt::white), Qt::BackgroundRole);
comboBox->setItemData(0, QColor(Qt::black), Qt::ForegroundRole);
comboBox->setItemData(1, QColor(Qt::red), Qt::BackgroundRole);
comboBox->setItemData(1, QColor(Qt::white), Qt::ForegroundRole);
comboBox->setItemData(2, QColor(Qt::darkGreen), Qt::BackgroundRole);
comboBox->setItemData(2, QColor(Qt::white), Qt::ForegroundRole);

QPalette p = comboBox->palette();
p.setColor(QPalette::Highlight, Qt::transparent);
comboBox->setPalette(p);

p = comboBox->view()->palette();
p.setColor(QPalette::Highlight, Qt::transparent);

comboBox->view()->setPalette(p);

问题是 QComboBox 当前的颜色是在弹出窗口中选择项目时的突出显示颜色。我希望每个 QComboBox 项目保持相同的颜色。图片显示了我遇到的问题。

enter image description here enter image description here enter image description here

最佳答案

如果我正确理解了这个问题,您希望完全删除突出显示的颜色,以便鼠标光标下的项目只能由虚线框区分。

一种方法如下:我们创建继承自 QItemDelegate 的类。 (通常简单的QItemDelegate 负责绘制QComboBox 项)。我们像这样覆盖paint函数:

class SelectionKillerDelegate : public QItemDelegate
{
virtual void paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const override
{
QStyleOptionViewItem myOption = option;
myOption.state &= (~QStyle::State_Selected);
QItemDelegate::paint (painter, myOption, index);
}
};

基本上我们只是使用普通的绘制函数函数,但假设所有项目都没有 QStyle::State_Selected正在 QItemDelegate::paint 内的多个函数中进行检查,最重要的是 drawBackground遗憾的是,这不是虚拟的。

当我们只是使用 comboBox->setItemDelegate (new SelectionKillerDelegate)使用我们的委托(delegate)而不是简单的 QItemDelegate .就这样。

好消息是焦点项目是使用 QStyle::State_HasFocus 确定的。因此即使使用此委托(delegate),鼠标光标指向的项目的虚线框仍然可见。

关于Qt如何更改特定QComboBox项目的突出显示颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21440282/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com