开发者

How to know if a QLineEdit got focus?

I want to be able to know if in the QLineEdit it was a click. So I guess I should reimplement the following function(??):

void QLineEdit::focusInEvent ( QFocusEvent * e )   [virtual protected]

How should I do that?

Also, please tell me how to use focusInEvent() function in order to know if QLineEdit myEdit; object got focus.

EDIT: I have written the following funct开发者_开发知识库ion:

bool LoginDialog::eventFilter(QObject *target, QEvent *event)
{
    if (target == m_passwordLineEdit)
    {
        if (event->type() == QEvent::FocusIn)
        {
            if(checkCapsLock())
            {
                QMessageBox::about(this,"Caps Lock", "Your caps lock is ON!");

            }
            return true;

        }
    }
    return QDialog::eventFilter(target, event);
}

And have registered m_passwordLineEdit in LoginDialog class constructor like this:

m_passwordLineEdit->installEventFilter(this);

And it's falling into an infinite loop of MessageBox-es. Please help me to resolve this situation. Actually I would like to implemet this function with a pop-up window (not with a QMessageBox). Is it OK to use QLabel for that need?


Also, please tell me how to use focusInEvent() function in order to know if QLineEdit myEdit; object got focus.

You should connect yourself to the following SIGNAL :

void QApplication::focusChanged ( QWidget * old, QWidget * now )   [signal]

When the new QWidget is your QLineEdit, you know it got focus !

Hope it helps !


Something like that:

class YourWidget : public QLineEdit
{
    Q_OBJECT

    protected:

    void focusInEvent(QFocusEvent* e);
};

In the .cpp file:

void YourWidget::focusInEvent(QFocusEvent* e)
{
    if (e->reason() == Qt::MouseFocusReason)
    {
      // The mouse trigerred the event
    }

    // You might also call the parent method.
    QLineEdit::focusInEvent(e);
}

You can find the list of all possible reasons on this page.


If you want to know when someone clicks in a widget, you should override mousePressEvent (QMouseEvent* event). A focusInEvent can be triggered by other sources than a mouse click.

For example:

class MyLineEdit : public QLineEdit
{
        Q_OBJECT
    public:
        //...
    protected:
         void mousePressEvent(QMouseEvent* event)
         {
              //pass the event to QLineEdit
              QLineEdit::mousePressEvent(event);
              //register the click or act on it
         }
};

If you do want to know when your widget receives focus, do the same with a focusInEvent of course.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜