[Interest] Proper way to track mouse leaving a widgets boundary

Volker Hilsheimer volker.hilsheimer at qt.io
Tue Aug 16 19:37:58 CEST 2022


> On 16 Aug 2022, at 18:45, Scott Bloom <scott at towel42.com> wrote:
> 
> I have a QTextEdit derived class, that sets setMouseTracking( true ) in the constructor.  Note, this isn’t about QTextEdit and should I use QTextBrowser.  Ive had this issue multiple times over the last 20 years of Qt development, and the solution has always been the same and I am not convinced it’s the correct way.
>  
> When there is a mouseMoveEvent in which the anchor at the mouse position is not empty, I override the cursor.
>  
> When the anchor at the point is empty, I restore the cursor
>  
> On mouseReleaseEvent I open the URL from the anchor.  
> 
> All works great (yes I know QTextBrowser should be able to be used, but there are some issues with that, and its not the issue)
>  
> The problem is, when the mouse leaves the widget there isn’t a “mouseLeaveEvent” so if the mouse is able to leave with the cursor overridden, it stays overridden.
>  
> The workaround, I added a eventFilter on the parent widget.  If the parent widget receives any event and the globalPos of the cursor (using QCursor::pos() ) is outside the widget its restores the cursor.  It works, however it seems a bit hackish
>  
> What is the “proper” methodology for tracking when a mouse leaves the widget? Ive tried various methods through the years, and this is the way that I find works
>  
> Full source for the widget can be found here
> https://github.com/towel42-com/SABUtils/blob/trunk/HyperLinkLineEdit.cpp
> https://github.com/towel42-com/SABUtils/blob/trunk/HyperLinkLineEdit.h
>  
> Thanks.
> 
> Scott


Hey Scott,

This should be a job for a QWidget::leaveEvent override:

https://doc.qt.io/qt-6/qwidget.html#leaveEvent


Volker



More information about the Interest mailing list