How can I change the mouse icon when the mouse is over the text in item delegate?
I have this part, but I can’t find any example to change the mouse pointer.
What am I missing?
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);
}
}
}
First of all you will need the mouse position. You can get it using the
QCursor::posstatic function.Notice that the result is in global screen coordinates, so you will have to translate it in widget coordinates. Let’s assume that the widget on which you are using the delegate is called
myWidget. In order to do the translation you will need themapFromGlobalfunction ofQWidgetFinally you are going to need the
indexAtfromQAbstractItemViewwhich returns the model index of the item at the viewport coordinates point.If
myViewis the name of the view you are using then the index at the current position is:Notice that you may need the
viewport()in order to be precise. In this case in order to map the global coordinates you will need:Finally you have to check if the returned index from the
itemAtis the same with the index in yourpaintfunction. If yes change the cursor to whta you want, else restore the default cursorThis is the basic idea. Another option would be to reimplement the
mouseMoveEventand implement the functionality there. Check this blog post for more details.