Created
March 1, 2020 11:10
-
-
Save pedrolcl/947046fd9765aedcd7f23a41819447db to your computer and use it in GitHub Desktop.
Movable QLabel using the mouse. Stackoverflow question: https://stackoverflow.com/questions/60463917/how-to-make-qlabel-of-qt-draggable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QLabel> | |
#include <QMouseEvent> | |
#include <QMainWindow> | |
#include <QApplication> | |
class MovableLabel : public QLabel | |
{ | |
public: | |
MovableLabel(QWidget* parent = nullptr): QLabel(parent) | |
{ | |
setAlignment(Qt::AlignCenter); | |
setFrameStyle(QFrame::StyledPanel | QFrame::Raised); | |
setLineWidth(2); | |
} | |
void mousePressEvent(QMouseEvent *event) override | |
{ | |
if (event->button() == Qt::LeftButton) { | |
QApplication::setOverrideCursor(QCursor(Qt::ClosedHandCursor)); | |
m_pos = event->pos(); | |
} | |
} | |
void mouseMoveEvent(QMouseEvent *event) override | |
{ | |
if (!m_pos.isNull()) { | |
move(mapToParent(event->pos() - m_pos)); | |
} | |
} | |
void mouseReleaseEvent(QMouseEvent *event) override | |
{ | |
if (event->button() == Qt::LeftButton) { | |
m_pos = QPoint(); | |
QApplication::restoreOverrideCursor(); | |
} | |
} | |
private: | |
QPoint m_pos; | |
}; | |
class MainWindow : public QMainWindow | |
{ | |
public: | |
MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) | |
{ | |
resize(600,400); | |
auto label = new MovableLabel(this); | |
label->setText("Move Me!"); | |
label->move(50, 50); | |
} | |
}; | |
int main(int argc, char *argv[]) | |
{ | |
QApplication a(argc, argv); | |
MainWindow w; | |
w.show(); | |
return a.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment