mousePressEvent and QGroupBox
Hi all,
I'm trying to build a custom widget that act like a button, but with more feature, like icons and multple labels...
Like any button I'd like to start a "callback" when the button is clicked. I think that the signal slot model does not work for this inter class case.
So I try the following code:
header
Code:
{
Q_OBJECT
public:
~CallButton();
protected:
};
and. cpp
Code:
CallButton
::CallButton(QWidget *parent
){
label
= new QLabel("Label...");
icon->setPixmap(pixmap);
mainLayout->addWidget(label);
mainLayout->addWidget(icon);
mainLayout->insertStretch(1);
groupBox
->setStyleSheet
(QString::fromUtf8("\ QGroupBox {\
background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\
stop: 0 #FFFFFF, stop: 1 #E0E0E0);\
border: 2px solid gray;\
border-radius: 5px;\
}"));
groupBox->resize(180,60);
groupBox->setLayout(mainLayout);
}
void CallButton
::mousePressEvent ( QMouseEvent * event
) {
groupBox
->setStyleSheet
(QString::fromUtf8("\ QGroupBox {\
background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\
stop: 0 #E0E0E0, stop: 1 #FFFFFF);\
border: 2px solid gray;\
border-radius: 5px;\
}"));
}
CallButton::~CallButton()
{
delete groupBox;
delete label;
delete icon;
}
The application compile and run, but the event is not launched when I left click inside the button (the event is launched when I left click outside the QGroupBox area and anywhere where I right click).
Why the left click does not work?
Thank's in advance to everyone,
Stefano.
Re: mousePressEvent and QGroupBox
Read more about installEventFilter and eventFilter.
http://doc.qt.nokia.com/4.6/qobject.html#eventFilter
Re: mousePressEvent and QGroupBox
Thanks tbscope,
The eventFilter solution works! I have made the following method, but I am a little scared about the performace of this solution....
Anyone has a more efficient implementation?
Code:
{
if (obj == groupBox) {
if (event
->type
() == QEvent::MouseButtonPress || event
->type
() == QEvent::MouseButtonDblClick) { groupBox
->setStyleSheet
(QString::fromUtf8(PRESS_STYLE
));
return true;
} else if (event
->type
() == QEvent::MouseMove) { // check if the pointer goes outside object area
QMouseEvent *mouseEvent
= static_cast<QMouseEvent
*>
(event
);
QGroupBox *groupBoxObj
= static_cast<QGroupBox
*>
(obj
);
if( mouseEvent->x() < 0 || mouseEvent->x() > groupBoxObj->width()
|| mouseEvent->y() < 0 || mouseEvent->y() > groupBoxObj->height() ){
groupBox
->setStyleSheet
(QString::fromUtf8(RELEASE_STYLE
));
}
return true;
} else if (event
->type
() == QEvent::MouseButtonRelease) { groupBox
->setStyleSheet
(QString::fromUtf8(RELEASE_STYLE
));
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QWidget::eventFilter(obj, event
);
}
}