C++ (Qt)#pragma once #include <QtWidgets/QWidget> #include <QPen> class MyScene : public QWidget{public: MyScene( QWidget * parent = nullptr ); void paintEvent( QPaintEvent * event ) override; protected: void mousePressEvent( QMouseEvent * event ) override; void mouseMoveEvent( QMouseEvent * event ) override; void mouseReleaseEvent( QMouseEvent * event ) override; private: bool _leftPressed; QPen _pen; QPointF _startPoint; QPointF _endPoint; QImage * _image;};
C++ (Qt)#include <QPaintEvent> #include <QPainter>#include <QImage>#include <QTimer> const int SZ = 1000; MyScene::MyScene( QWidget * parent ): QWidget( parent ){ _pen.setWidth( 1 ); _pen.setColor( Qt::red ); _leftPressed = false; _image = new QImage( SZ, SZ, QImage::Format_ARGB32_Premultiplied ); _image->fill( Qt::white ); resize( SZ, SZ ); QTimer * timer = new QTimer( this ); timer->setInterval( 16 ); connect( timer, SIGNAL( timeout() ), this, SLOT( update() ) ); timer->start();} void MyScene::paintEvent( QPaintEvent * ){ QPainter painter( this ); painter.drawImage( 0, 0, *_image );} void MyScene::mousePressEvent(QMouseEvent * event){ if ( event->button() == Qt::LeftButton ) { _leftPressed = true; _startPoint = event->pos(); }} void MyScene::mouseMoveEvent(QMouseEvent * event){ if ( _leftPressed ) { _endPoint = event->pos(); QPainter painter( _image ); painter.drawLine( _startPoint, _endPoint ); _startPoint = _endPoint; }} void MyScene::mouseReleaseEvent(QMouseEvent * event){ _leftPressed = false;}
void MainWindow::mouseMoveEvent(QMouseEvent * event){ qDebug() << event;}void MainWindow::mousePressEvent(QMouseEvent * event){ qDebug() << event;}void MainWindow::mouseReleaseEvent(QMouseEvent * event){ qDebug() << event;}
QMouseEvent(MouseButtonPress, LeftButton, localPos=95,219, screenPos=855,589)QMouseEvent(MouseMove, buttons=LeftButton, localPos=96,219, screenPos=856,589)QMouseEvent(MouseMove, buttons=LeftButton, localPos=97,219, screenPos=857,589)QMouseEvent(MouseMove, buttons=LeftButton, localPos=98,219, screenPos=858,589)QMouseEvent(MouseMove, buttons=LeftButton, localPos=99,219, screenPos=859,589)QMouseEvent(MouseMove, buttons=LeftButton, localPos=100,219, screenPos=860,589)QMouseEvent(MouseMove, buttons=LeftButton, localPos=101,219, screenPos=861,589)QMouseEvent(MouseButtonRelease, LeftButton, localPos=101,219, screenPos=861,589)