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?

有帮助吗?

解决方案

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.

enter image description here

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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top