Mouse events QT

泪湿孤枕 提交于 2019-12-23 05:26:01

问题


I want to to allow user to select a region with mouse, like you can do mostly everywhere.For more clarity just imagine your desktop on Windows, and click the left button and move the mouse with the button holed. The following will happen: you will see how the region that your mouse passed is highlighted with a rectangle. That is exactly what I want to do.

p.s. Mathematically I know how to calculate, and also know how to draw the rectangle by being able to track mouse position when it is pressed.

Q1: How to track mouse position? Q2: Any alternative way to do what I want?


回答1:


The simplest way is to use the Graphics View Framework. It provides mechanism for item selection, display of a rubber band rectangle, detection of intersection of the rubber band with the items, etc. Below is a self contained example. It lets you select and drag multiple items using either Ctrl/Cmd-click to toggle selection, or rubber banding.

OpenGL is used to render the background, and you can put arbitrary OpenGL content there.

main.cpp

#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGLWidget>

static qreal rnd(qreal max) { return (qrand() / static_cast<qreal>(RAND_MAX)) * max; }

class View : public QGraphicsView {
public:
    View(QGraphicsScene *scene, QWidget *parent = 0) : QGraphicsView(scene, parent) {
        setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
        setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    }
    void drawBackground(QPainter *, const QRectF &) {
        QColor bg(Qt::blue);
        glClearColor(bg.redF(), bg.greenF(), bg.blueF(), 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    }
};

void setupScene(QGraphicsScene &s)
{
    for (int i = 0; i < 10; i++) {
        qreal x = rnd(1), y = rnd(1);
        QAbstractGraphicsShapeItem * item = new QGraphicsRectItem(x, y, rnd(1-x), rnd(1-y));
        item->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
        item->setPen(QPen(Qt::red, 0));
        item->setBrush(Qt::lightGray);
        s.addItem(item);
    }
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene s;
    setupScene(s);
    View v(&s);
    v.fitInView(0, 0, 1, 1);
    v.show();
    v.setDragMode(QGraphicsView::RubberBandDrag);
    v.setRenderHint(QPainter::Antialiasing);
    return a.exec();
}


来源:https://stackoverflow.com/questions/18537558/mouse-events-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!