C++ (Qt)void QObject::timerEvent ( QTimerEvent * event ) [virtual protected]
C++ (Qt)#include <QWidget>#include <QMoveEvent>#include <QResizeEvent>#include <QTimer>#include <QApplication>#include <QDesktopWidget>#include <QDebug>#include <QPainter>#include <QSizeGrip>#include <QHBoxLayout> class MovableWindow: public QWidget{public: MovableWindow( QWidget * parent = 0 ) : QWidget( parent ) { setWindowFlags( Qt::Window | Qt::FramelessWindowHint ); QHBoxLayout * layout = new QHBoxLayout(); layout->setContentsMargins( 0, 0, 0, 0 ); layout->addWidget( new QSizeGrip( this ), 0, Qt::AlignLeft | Qt::AlignTop ); layout->addWidget( new QSizeGrip( this ), 0, Qt::AlignRight | Qt::AlignBottom ); setLayout( layout ); setMinimumSize( 50, 50 ); resize( 150, 150 ); } private: bool isMousePress; QPoint oldPosition; protected: void mousePressEvent( QMouseEvent * event ) { if ( event->button() == Qt::LeftButton ) { oldPosition = event->pos(); isMousePress = true; } } void mouseReleaseEvent( QMouseEvent * ) { isMousePress = false; } void mouseMoveEvent( QMouseEvent * event ) { if ( isMousePress ) { QPoint delta = event->pos() - oldPosition; move( pos() + delta ); } } void paintEvent( QPaintEvent * ) { QPainter painter( this ); painter.setPen( QPen( Qt::black, 2.0 ) ); painter.drawRect( rect() ); }}; class AttachableWindow: public MovableWindow{ Q_OBJECT public: explicit AttachableWindow( QWidget * parent = 0 ) : MovableWindow( parent ) { } private: int timerId; protected: void timerEvent( QTimerEvent * event ) { const QRect & availableGeometry = QDesktopWidget().availableGeometry(); int d_x = availableGeometry.x(); int d_y = availableGeometry.y(); int d_width = availableGeometry.width(); int d_height = availableGeometry.height(); int distance = 10; if ( x() >= d_x && x() <= distance ) move( d_x, y() ); if ( y() >= d_y && y() <= distance ) move( x(), d_y ); if ( x() + width() >= d_width - distance && x() + width() <= d_width ) move( d_width - width(), y() ); if ( y() + height() >= d_height - distance && y() + height() <= d_height ) move( x(), d_height - height() ); } void mousePressEvent( QMouseEvent * event ) { MovableWindow::mousePressEvent( event ); timerId = startTimer( 333 ); } void mouseReleaseEvent( QMouseEvent * event ) { MovableWindow::mouseReleaseEvent( event ); killTimer( timerId ); }};
C++ (Qt) void timerEvent( QTimerEvent * ) { if( event->timerId() != timerId ) { killTimer( event->timerId() ); return; } ...