#include #include #include #include #include #include #include #include class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); }; class GraphicsView : public QGraphicsView { public: GraphicsView(QWidget * parent); void initialiseScene(); bool event(QEvent * event) override; bool gestureEvent(QGestureEvent * event); void setScale(double scale); QGraphicsScene mScene; Qt::GestureState mLastState{ Qt::GestureState::NoGesture }; }; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setCentralWidget(new GraphicsView{ this }); } MainWindow::~MainWindow(){ } namespace { QRandomGenerator& rng() { static QRandomGenerator sRng; return sRng; } QColor randomColour() { return QColor{ rng().bounded(64, 255), rng().bounded(64, 255), rng().bounded(64, 255) }; } } GraphicsView::GraphicsView(QWidget * parent) : QGraphicsView{ parent } { setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setScene(&mScene); initialiseScene(); grabGesture(Qt::PinchGesture); } void GraphicsView::initialiseScene() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { mScene.addRect({ i * 100.0, j * 100.0, 100, 100 }, Qt::NoPen, QBrush{ ::randomColour() }); } } } bool GraphicsView::event(QEvent * event) { if (event->type() == QEvent::Gesture) { return gestureEvent(static_cast(event)); } else if (event->type() == QEvent::TouchBegin || event->type() == QEvent::TouchUpdate || event->type() == QEvent::TouchEnd) { qDebug() << "touch event" << static_cast(event)->points().size() << "points"; } return QGraphicsView::event(event); } bool GraphicsView::gestureEvent(QGestureEvent * event) { bool result{ false }; if (QGesture * gesture = event->gesture(Qt::PinchGesture)) { QPinchGesture * pinch{ static_cast(gesture) }; QPinchGesture::ChangeFlags changeFlags = pinch->changeFlags(); Qt::GestureState state = pinch->state(); if (state == Qt::GestureState::GestureFinished) { if (mLastState == Qt::GestureState::GestureStarted) { qDebug() << "gesture finished without updates"; } } mLastState = state; if (changeFlags & QPinchGesture::ScaleFactorChanged){ double scaleFactor = pinch->totalScaleFactor(); setScale(scaleFactor); } if (changeFlags & QPinchGesture::CenterPointChanged) { } if (gesture->state() == Qt::GestureFinished) { } result = true; } if (QGesture * gesture = event->gesture(Qt::TapGesture)) { } if (QGesture * gesture = event->gesture(Qt::TapAndHoldGesture)) { } return result; } void GraphicsView::setScale(double scale) { QTransform transform; transform.scale(scale, scale); setTransform(transform); } int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } #include "main.moc"