How to make a QLabel follow a mouse pointer and display over other widgets?
-
I was wondering how do you draw over other widgets in PyQt?
The intention is to make a binary indicator of X,Y cords with a pyQtGraph widget and I want to binarize the display of plotted dots on the graph to be displayed by the X Coordinated of the mouse and by a single or two labels to display the XY coordinated of the plotted graph near the mouse while following it.How would one approach it? (QToolTip option is out as it doesn't seem to respond well and isn't constantly ON)
I would like to know in general the way of overlaying widgets on top of other in an absolute way with XY pixel coordinates.
-
Hi,
You can use mouse tracking and move a QLabel along the mouse pointer.
-
In this case, you do not put the QLabel in a layout. You move it manually.
-
@SGaist That's what I don't understand how to do I'm got my redefinition of QMainWindow and set a plot widget as the central widget for now but how'd you add a QLabel of top of it and position it according to the mouse cursor position is something I can't find a solution for.
I'd be useful if an example of how'd you add a QLabel to the MainWindow and change it's position would be added here.
-
@MikeLemon said in How to make a QLabel follow a mouse pointer and display over other widgets?:
but how'd you add a QLabel of top of it
You create the QLabel, set its parent to your central widget, but do not add it to any layout, call show() on it.
"position it according to the mouse cursor position" - you get the mouse coordinates from the event, then call https://doc.qt.io/qt-5/qwidget.html#pos-prop on the label. -
#include <QMouseEvent> class MyMainWindow : public QMainWindow { Q_OBJECT public: explicit MyMainWindow (QWidget *parent = nullptr) : QMainWindow(parent) { setMouseTracking(true); m_myLabel = new QLabel(this); m_myLabel->setStyleSheet(QString("background-color:red")); m_myLabel->resize(160,40); } protected: void mouseMoveEvent(QMouseEvent *event) override { auto pos = event->pos(); m_myLabel->move(pos); m_myLabel->setText(QString("Mouse at: (%1 | %2)").arg(pos.x()).arg(pos.y())); } private: QLabel *m_myLabel; }; int main(int argc, char *argv[]) { QApplication a(argc, argv); MyMainWindow m; m.resize(400, 400); m.show(); a.exec(); } #include "main.moc"
I'm sure you're able to adapt this example for your case.