Created
April 6, 2014 08:34
-
-
Save mnafees/10003130 to your computer and use it in GitHub Desktop.
How to make a frameless QWidget 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
// Qt | |
#include <QApplication> | |
// MyWidget | |
#include "MyWidget.h" | |
int main( int argc, char* argv[] ) | |
{ | |
QApplication app( argc, argv ); | |
MyWidget widget; | |
widget.show(); | |
return app.exec(); | |
} |
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
// 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(); | |
} | |
} |
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
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!