[SOLVED] QWidget and QRects
-
Hi all!
I have a QWidget subclassed and I need to implement some repaints with mouse move event, but when I use the QRect contains to check if the mouse position is inside the QRect it gives me a different position as the drawed QRect.
What is going on here?
Code
fluxocaixawidget.h
@
#ifndef FLUXOCAIXAWIDGET_H
#define FLUXOCAIXAWIDGET_H#include <QWidget>
#include <QPainter>class fluxoCaixaWidget : public QWidget
{
Q_OBJECT
public:
explicit fluxoCaixaWidget(QWidget *parent = 0);QRect rectLinhaTempo();
protected:
void paintEvent(QPaintEvent *);
void mouseMoveEvent(QMouseEvent *);private:
bool dentro;
QRect linhaTempo;signals:
public slots:
};
#endif // FLUXOCAIXAWIDGET_H
@fluxocaixawidget.cpp
@
#include "fluxocaixawidget.h"#include <QDebug>
fluxoCaixaWidget::fluxoCaixaWidget(QWidget *parent) :
QWidget(parent)
{
this->setMouseTracking(true);
this->dentro = false;
}void fluxoCaixaWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);linhaTempo.setRect(20, this->parentWidget()->height() / 2 - 20, this->parentWidget()->width()-65, 30); QPen caneta; QBrush pincel(Qt::white); painter.setBrush(pincel); painter.drawRect(parentWidget()->rect()); if(this->dentro == true) { caneta.setColor(Qt::red); caneta.setWidth(4); } else { caneta.setColor(Qt::black); caneta.setWidth(2); } painter.setPen(caneta); painter.drawRect(linhaTempo);
}
void fluxoCaixaWidget::mouseMoveEvent(QMouseEvent *)
{
if(this->linhaTempo.contains(QCursor::pos()))
{
qDebug() << "OK";
this->dentro = true;
}
else
{
qDebug() << "Fora";
this->dentro = false;
}
this->update();
}
@ -
There are numerous coordinate systems in Qt applications: a global position (on the screen), a position relative to window frame, a position relative to window contents, a position relative to widget, etc. To make sure you are checking within the same coordinate system, you need to map the coordinates.
Quoting the documentation:
[quote]The functions pos(), x(), and y() give the cursor position relative to the widget that receives the mouse event. If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion.[/quote] -
SOLVED
Thanks for your help and time sierdzio.
Cheers!
@
void fluxoCaixaWidget::mouseMoveEvent(QMouseEvent *)
{
if(this->linhaTempo.contains(this->mapFromGlobal(QCursor::pos())))
{
qDebug() << "OK";
this->dentro = true;
}
else
{
qDebug() << "Fora";
this->dentro = false;
}
this->update();
}
@