使用QStyledItemDelegate将鼠标悬停在文本上时,如何更改鼠标指针?

use*_*898 1 c++ qt

当鼠标悬停在项目委托中的文本上时,如何更改鼠标图标?我有这个部分,但我找不到任何改变鼠标指针的例子.

我错过了什么?

   void ListItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                             const QModelIndex &index) const
    {
     if (index.isValid())
        {
      int j = index.column();
      if(j==4)
      {
       QString headerText_DisplayRole = index.data(Qt::DisplayRole).toString() ;
       QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter );

       QFont font = QApplication::font();
       QRect headerRect = option.rect;
       font.setBold(true);
       font.setUnderline(true);
       painter->setFont(font);
       painter->setPen(QPen(option.palette.brush(QPalette::Text), 0));
       const bool isSelected = option.state & QStyle::State_Selected;    
       if (isSelected)
        painter->setPen(QPen(option.palette.brush(QPalette::HighlightedText), 0));
       else
        painter->setPen(QPen(option.palette.brush(QPalette::Text), 0));
       painter->save();    
       painter->drawText(headerRect,headerText_DisplayRole);
       painter->restore();
       bool hover = false;
       if ( option.state & QStyle::State_MouseOver )
       {
           hover = true;
       }
       if(hover)
       {
        // THIS part i missing , how detect when mouse is over the text
        // and if its over how to change the icon of the mouse?
       }


      }
      else
      {
       QStyledItemDelegate::paint(painter, option, index);
      }
     }
    }
Run Code Online (Sandbox Code Playgroud)

pne*_*zis 8

首先,您需要鼠标位置.你可以使用QCursor::pos静态函数来获取它.

QPoint globalCursorPos = QCursor::pos();
Run Code Online (Sandbox Code Playgroud)

请注意,结果是全局屏幕坐标,因此您必须在窗口小部件坐标中进行转换.假设您调用使用该委托的小部件myWidget.为了进行翻译,你需要的mapFromGlobal功能QWidget

QPoint widgetPos = myWidget->mapFromGlobal(globalCursorPos);
Run Code Online (Sandbox Code Playgroud)

最后,您将需要indexAt从QAbstractItemView视口坐标点返回项的模型索引.

如果myView是您正在使用的视图的名称,那么当前位置的索引是:

QModelIndex currentIndex = myView->itemAt(widgetPos);
Run Code Online (Sandbox Code Playgroud)

请注意,viewport()为了精确,您可能需要它.在这种情况下,为了映射全局坐标,您需要:

QPoint viewportPos = myWidget->viewport()->mapFromGlobal(globalCursorPos);
Run Code Online (Sandbox Code Playgroud)

最后,您必须检查返回的索引itemAt是否与paint函数中的索引相同.如果是,则将光标更改为您想要的光标,否则恢复默认光标

if(hover)
{
     QPoint globalCursorPos = QCursor::pos();
     QPoint viewportPos = myWidget->viewport()->mapFromGlobal(globalCursorPos);
     QModelIndex currentIndex = myView->itemAt(widgetPos);

     if (currentIndex == index)
         QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor)); 
     else
         QApplication::restoreOverrideCursor(); 
}
Run Code Online (Sandbox Code Playgroud)

这是基本的想法.另一种选择是重新实现mouseMoveEvent并实现那里的功能.查看此博客文章了解更多详情.