void MyWidget::mousePressEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton) { this->move(e->globalPos()); } }
void MyWidget::mousePressEvent(QMouseEvent *e){ if (e->button() == Qt::LeftButton) { this->posPrev = e->globalPos(); }} void MyWidget::mouseMoveEvent(QMouseEvent *e){ QPoint dt = QPoint(this->posPrev - e->globalPos()); this->move(this->pos()-dt); this->posPrev = e->globalPos(); }
Pythonclass MyWidget(QWidget): def __init__(self, parent=None): super(MyWidget, self).__init__(parent) self.prevPos = QPoint(0, 0) def mousePressEvent(self, event): self.prevPos = event.globalPos() def mouseMoveEvent(self, event): dt = self.prevPos - event.globalPos() self.move(self.pos()-dt) self.prevPos = event.globalPos()
C++ (Qt)#include <QApplication>#include <QToolButton>#include <QScrollArea>#include <QMouseEvent> class Button : public QToolButton{public: Button( const QString& s, QWidget* parent = 0 ) : QToolButton( parent ) { setText( s ); setMouseTracking( true ); } protected: void mouseMoveEvent( QMouseEvent* e ) { if( drag_pos_ != QPoint() ) { move( pos() + ( e->globalPos() - drag_pos_ ) ); drag_pos_ = e->globalPos(); } } void mousePressEvent( QMouseEvent* e ) { raise(); drag_pos_ = e->globalPos(); setCursor( QCursor( Qt::SizeAllCursor ) ); } void mouseReleaseEvent( QMouseEvent* e ) { drag_pos_ = QPoint(); unsetCursor(); }private: QPoint drag_pos_;}; int main( int argc, char** argv ){ QApplication app( argc, argv ); QScrollArea w; Button b1( "Drag me", w.viewport() ); b1.move( 10, 10 ); Button b2( "Drag me", w.viewport() ); b1.move( 40, 40 ); w.show(); return app.exec();}
C++ (Qt) move( pos() + ( e->globalPos() - drag_pos_ ) ); drag_pos_ = e->globalPos();