Skip to content

Instantly share code, notes, and snippets.

@mnafees
Created April 6, 2014 08:34
Show Gist options
  • Save mnafees/10003130 to your computer and use it in GitHub Desktop.
Save mnafees/10003130 to your computer and use it in GitHub Desktop.
How to make a frameless QWidget draggable?
// Qt
#include <QApplication>
// MyWidget
#include "MyWidget.h"
int main( int argc, char* argv[] )
{
QApplication app( argc, argv );
MyWidget widget;
widget.show();
return app.exec();
}
// Qt
#include <QMouseEvent>
// MyWidget
#include "MyWidget.h"
MyWidget::MyWidget( QWidget *parent ) :
QWidget( parent ),
_mousePressed(false),
_mousePosition(QPoint())
{
setWindowFlags( Qt::FramelessWindowHint );
}
MyWidget::~MyWidget()
{
// delete stuff.
}
void MyWidget::mousePressEvent( QMouseEvent *e )
{
if ( e->button() == Qt::LeftButton ) {
_mousePressed = true;
_mousePosition = e->pos();
}
}
void MyWidget::mouseMoveEvent( QMouseEvent *e )
{
if ( _mousePressed ) {
move( mapToParent( e->pos() - _mousePosition ) );
}
}
void MyWidget::mouseReleaseEvent( QMouseEvent *e )
{
if ( e->button() == Qt::LeftButton ) {
_mousePressed = false;
_mousePosition = QPoint();
}
}
#ifndef MYHEADER_H
#define MYHEADER_H
// Qt
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget( QWidget *parent = 0 );
~MyWidget();
protected:
virtual void mousePressEvent( QMouseEvent *e );
virtual void mouseMoveEvent( QMouseEvent *e );
virtual void mouseReleaseEvent( QMouseEvent *e );
private:
bool _mousePressed;
QPoint _mousePosition;
};
#endif
@edipo2s
Copy link

edipo2s commented May 13, 2018

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment