鼠标事件QT [英] Mouse events QT

查看:108
本文介绍了鼠标事件QT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望允许用户使用鼠标来选择一个区域,就像您几乎可以在任何地方进行操作一样.为更加清晰起见,请想象一下Windows上的桌面,然后单击左键并在鼠标上打孔的情况下移动鼠标.将发生以下情况:您将看到如何用矩形突出显示鼠标经过的区域.那正是我想做的.

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.数学上,我知道如何计算,也知道如何通过在按下鼠标时跟踪鼠标的位置来绘制矩形.

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:如何跟踪鼠标位置? Q2:做我想要的任何其他方式吗?

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

推荐答案

最简单的方法是使用Graphics View Framework.它提供了项目选择的机制,橡皮筋矩形的显示,橡皮筋与项目的相交的检测等.以下是一个自包含的示例.它使您可以使用Ctrl/Cmd单击来切换选择或橡皮筋来选择和拖动多个项目.

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用于渲染背景,您可以在其中放置任意OpenGL内容.

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();
}

这篇关于鼠标事件QT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆