Skip to content

Instantly share code, notes, and snippets.

@pedrolcl
Created March 1, 2020 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrolcl/947046fd9765aedcd7f23a41819447db to your computer and use it in GitHub Desktop.
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
#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