How to hide/unhide QWidget on hover.
-
I am trying to create a media player.
I have a QVideoWidget that contains a QWidget, as a child inside of it, at the bottom.
This is how it currently looks:
It is fine, but I want to make sure that the QWidget at the bottom containing the tools will only show up if the user actually hovers over the video (in this case being the QVideoWidget)
How can I achieve this?
-
#include <QApplication> #include <QMouseEvent> #include <QVideoWidget> class HoverVideoWidget : public QVideoWidget { public: HoverVideoWidget(QWidget *parent = nullptr) : QVideoWidget(parent) { setMouseTracking(true); // Enable mouse tracking to get hover events } protected: void enterEvent(QEvent *event) override { // Called when the mouse enters the widget setStyleSheet("background-color: lightblue;"); // Set the background color to light blue } void leaveEvent(QEvent *event) override { // Called when the mouse leaves the widget setStyleSheet(""); // Reset the background color to default } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); HoverVideoWidget player; player.show(); return app.exec(); }
-
Enable
mouseTracking
on yourQVideoWidget
withvideoWidget->setMouseTracking(true);
Re-implement
enterEvent(QEnterEvent *)
andleaveEvent(QEvent *)
and call a function to hide/show the child widget with your controls (QHoverEvent
might also work. Maybe even better).
To make it look better, you could use something likeQPropertyAnimation
to let the widget fade-in and fade-out again, as soon as you leave the area.You could also install an
eventFilter
on your main widget, where you filter events coming from your video widget. Check, if event types areQEvent::Enter
orQEvent::Leave
and then handle it as needed. -
@Pl45m4 Thank you for your answer. Just one more question:
If I am not mistaking in order to re-implement the events of the QVideoWidget I would have to make a subclasses of it and then insert virtual functions and overwrite them. Correct? But I currently have a QVideoWidget set in the designer ui form using the promote to method. How can I achieve this without all that work?
-
#include <QApplication> #include <QMouseEvent> #include <QVideoWidget> class HoverVideoWidget : public QVideoWidget { public: HoverVideoWidget(QWidget *parent = nullptr) : QVideoWidget(parent) { setMouseTracking(true); // Enable mouse tracking to get hover events } protected: void enterEvent(QEvent *event) override { // Called when the mouse enters the widget setStyleSheet("background-color: lightblue;"); // Set the background color to light blue } void leaveEvent(QEvent *event) override { // Called when the mouse leaves the widget setStyleSheet(""); // Reset the background color to default } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); HoverVideoWidget player; player.show(); return app.exec(); }
-