PDA

View Full Version : Changing QPushButton text colour with mouseMoveEvent



Misenko
10th June 2008, 17:18
Hi
In the first place excuse my english I am Slovak :D

So, I am trying to change text colour on my QPushButton when my mouse is over it. Actually it is not a QPushButton but a class based on it becouse i want only to show the text not a frame. The first colour is blue. The second colour is green and it is sets when mouse is over the button. The third colour is orange and it is sets when the button is clicked. This working but when I move the mouse over it and then away the text colour is still green but I want to chenge it back to blue. This is my code:


#include "cudlik.h"
#include <QPainter>
#include <QMouseEvent>
#include <QPushButton>

Cudlik::Cudlik(const QString & text, QPushButton *parent)
: QPushButton(parent)
{
setText(text);
farba=(QColor(37,123,218));
setMouseTracking(true);
}

Cudlik::~Cudlik()
{

}

void Cudlik::paintEvent(QPaintEvent *event)
{
painter = new QPainter(this);
painter->setRenderHint(QPainter::Antialiasing);
painter->setPen(farba);
painter->setBrush(QBrush(farba));
painter->drawText(10,10,text());
delete painter;
}

void Cudlik::mouseMoveEvent(QMouseEvent* event)
{
QPoint kurzor = event->globalPos();
QPoint napis = pos();
if (kurzor.x()<napis.x() || kurzor.x()>napis.x()+width() || kurzor.y()<napis.y() || kurzor.y()>napis.y()+height())
{
farba=(QColor(37,123,218));
//update();
}
else
{
farba=(QColor(108,203,52));
update();
}
}

void Cudlik::mousePressEvent(QMouseEvent* event)
{
farba=QColor(238,105,17);
move(x()+2,y()+4);
update();
}

void Cudlik::mouseReleaseEvent(QMouseEvent* event)
{
move(x()-2,y()-4);
emit clicked();
update();
}

I tried to solve it by the if condition but it doesnt work. I think that the mouseMoveEvent is emited only when cursor is over the widget so this condition is useless. And I dont know how to solve this problem. Please help.

jpn
10th June 2008, 17:53
You could do it with QWidget::enterEvent() and QWidget::leaveEvent() but I'd recommend taking a look at style sheets (http://doc.trolltech.com/4.4/stylesheet.html).