【问题标题】:QListWidget disable mouseover highlightQListWidget 禁用鼠标悬停高亮
【发布时间】:2017-02-22 22:05:20
【问题描述】:

我有一个 QListWidget,其中有几个 QListWidgetItems,只包含文本但背景颜色不同。默认情况下,当我将鼠标悬停在项目上时,项目会以蓝色条突出显示。如何禁用突出显示?

我使用的代码

//add spacer
QListWidgetItem *spacer = new QListWidgetItem("foo");
spacer->setBackgroundColor(QColor(Qt::gray));
spacer->setFlags(Qt::ItemIsEnabled);    //disables selectionable
ui->listWidget->addItem(spacer);

提前致谢。

spacer 是带有当天名称的灰色项目

编辑:添加图片链接(截图工具工具隐藏鼠标,第6项突出显示)

【问题讨论】:

    标签: qt qt5 highlight qlistwidget qlistwidgetitem


    【解决方案1】:

    我设法通过覆盖QStyledItemDelegate::paint 方法的自定义项委托来做到这一点。

    void ActivitiesItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
    
    //determine if index is spacer
    //TODO non-hacky spacer detection
    bool spacer = false;
    QString text = index.data().toString();
    if(        ( text == "Monday")
            || ( text == "Tuesday")
            || ( text == "Wednesday")
            || ( text == "Thursday")
            || ( text == "Friday")
            || ( text == "Saturday")
            || ( text == "Sunday")
    ){
        spacer = true;
    }
    
    if(option.state & QStyle::State_MouseOver){
        if(spacer){
            painter->fillRect(option.rect, QColor(Qt::gray));
        }else{
            painter->fillRect(option.rect, QColor(Qt::white));
        }
        painter->drawText(option.rect.adjusted(3,1,0,0), text);
        return;
    }
    
    //default
    QStyledItemDelegate::paint(painter, option, index);
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 Qt CSS 覆盖“悬停”的背景,如果您使用的是“灰色”颜色:

      spacer->setStylesheet("*:hover {background:gray;}");
      

      或者按照Qt Style sheet examples中的描述设置整个列表的样式

      QListView::item:hover {
          background: gray
      }
      

      【讨论】:

      • 我在列表中有 2 种背景颜色。如何定义一个背景为白色而另一个为灰色?
      • 您可以使用 QListView::item:alternate { background: #EEEEEE; 设置第二种颜色}
      • 使用备用属性是不正确的。当间隔项目下有更多活动时,颜色应用错误。我正在寻找一种基于 QListWidgetItems 文本设置悬停背景的方法。或者可能分配一个自定义类型属性以从 QSS 中引用?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      相关资源
      最近更新 更多