Qt 5.7如何限制小部件内的鼠标移动

时间:2017-02-22 18:27:24

标签: c++ qt restrictions

当我拖动自定义小部件时,我希望鼠标在QScrollArea中“卡住”。我使QScrollArea成为一个名为MyScrollArea的子类,因此我可以重新实现事件mouseMoveEvent。这是MyScrollArea子类:

myscrollarea.h

#ifndef MYSCROLLAREA_H
#define MYSCROLLAREA_H

#include <QScrollArea>
#include <QDebug>
#include <QtGui>

class MyScrollArea : public QScrollArea
{
    Q_OBJECT
public:
    explicit MyScrollArea(QWidget *parent = 0);

signals:
    void changeLabel(QString);

public slots:

protected:
    void leaveEvent(QEvent *event);

    void mouseMoveEvent(QMouseEvent *event);

private:
    int mouseX, mouseY;
};

#endif // MYSCROLLAREA_H

myscrollarea.cpp

#include "myscrollarea.h"

MyScrollArea::MyScrollArea(QWidget *parent)
    : QScrollArea(parent)
{
    this->setMouseTracking(true);
    mouseX = 0;
    mouseY = 0;
}

void MyScrollArea::leaveEvent(QEvent *event)
{
    qDebug() << "LEFT!";
}

void MyScrollArea::mouseMoveEvent(QMouseEvent *event)
{
    mouseX = event->x();
    mouseY = event->y();
    event->accept();
    emit changeLabel(QString::number(mouseX) + ", " + QString::number(mouseY));
}

即使鼠标跟踪设置为true,我也只能在按住按钮时获得mouseMoveEvent

我的问题是:

  1. 如何在所有动作中触发mouseMoveEvent
  2. 当我拖动我创建的自定义小部件时,如何将光标设置到最后位置(在“QScrollArea”内)?

0 个答案:

没有答案