PDA

View Full Version : QWidget and QRects



guidupas
29th May 2014, 00:56
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();
}

Rajesh.Rathod
29th May 2014, 06:25
Read MapToParent and see if it is required to do in your case while setting rect in paint event.

wysota
29th May 2014, 10:08
Why are you accessing parentWidget() in the paint event of a different widget? The widget paints on itself, not on its parent. There may even be no parent widget at all. What is the effect you are trying to achieve?

guidupas
29th May 2014, 17:00
Thanks for the reply.

I need to paint relatively to the parent width and check if the muse is inside the painted object.

guidupas
29th May 2014, 19:36
SOLVED

Thanks for your help and time wysota.

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