PDA

View Full Version : Forcing a QWidget to lose focus



Polnareff
4th November 2010, 16:01
Hi,

I have a class which derives from QSpinBox. In it, I've overriden the following event functions:

focusInEvent
focusOutEvent
keyPressEvent

The functionality I've implemented makes it so that the value of the spinbox has only actually 'changed' when the user has pressed the enter key or lost focus (i.e. tabbed or clicked away). How I do so doesn't really matter for this question.

I maintain a variable PrevValue which holds the original value of the spinbox before the user is finished editting it. I'd like to add the use of the ESC key to return the value to the PrevValue as well as lose focus of the spinbox. My code:



void MySpinBox::focusInEvent(QFocusEvent *a_pEvent)
{
setStyleSheet(QString::fromUtf8("font: bold;"));
QAbstractSpinBox::focusInEvent(a_pEvent);
}
void MySpinBox::focusOutEvent(QFocusEvent *a_pEvent)
{
setStyleSheet(QString::fromUtf8("font: normal;"));
QAbstractSpinBox::focusOutEvent(a_pEvent);
}
void MySpinBox::keyPressEvent(QKeyEvent *a_pEvent)
{
if( a_pEvent->key() == Qt::Key_Escape )
{
setValue(PrevValue);
this->focusOutEvent(new QFocusEvent(QEvent::FocusOut, Qt::MouseFocusReason));
}
else
QAbstractSpinBox::keyPressEvent(a_pEvent);
}

As you can see, the focus events simply change the style of the spinbox, nothing more, and the keyPressEvent simply sets the value, and then forces a focus out event.

This works fine, the only problem is that once it's lost focus this way, nothing else in my form has gained focus. So if I press ESC and then click the spinbox again, the focusInEvent no longer works. I tried using Qt::MouseFocusReason above, as a test, to hopefully make it think it had clicked elsewhere...but of course, there is still no object with focus so it doesn't work.

Is there a simpler way to do this, or do I need to make some kind of focus dummy?

Thanks!

high_flyer
5th November 2010, 10:24
Without really to have read your code, in principal however, if all you want is to lose focus from this widget but retain focus in the application, why not just move the focus to the next tab index widget?