如何使用focusInEvent和focusOutEvent

时间:2014-01-16 06:53:38

标签: c++ qt qmainwindow qevent

我正在实施一个应用程序,其中我有3个QToolButton,当焦点出现在任何QToolButton时,它应resize。 我的一个朋友给了我答案,但我无法弄清楚,因为我在我的mainWindow中继承了QMainWindow类。他告诉我继承QToolButton。但是会发生多重继承问题。那么如何使用focusInEvent()

MyCode:
mywindow.h :

class mywindow : public QMainWindow
{
    Q_OBJECT
public:
    mywindow() ;

protected:
    void keyReleaseEvent(QKeyEvent *event); 
    void focusInEvent(QFocusEvent *event);
    void focusOutEvent(QFocusEvent *event);

private:
    QWidget *widget;
    QStackedWidget *stack1;
    QToolBar *tool;
    QListWidget *list1;
    QListWidget *list2;
    QVBoxLayout *vertical;
    QToolButton *button1;
    QToolButton *button2;
    QToolButton *button3;

public slots:
    void fileNew();
    void file();
    bool eventFilter(QObject *object, QEvent *event);

};

mywindow.cpp:

mywindow::mywindow() : QMainWindow()
{   
  //some code
}

我的朋友的代码,我必须合并:

class mywindow : public QToolButton
{
    private:
         int originalWidth, originalHeight;
         int bigWidth, bigHeight;
};

void focusInEvent ( QFocusEvent * event ) { 
                   resize(bigWidth,bigHeight); 
                   QToolButton::focusInEvent(event); 
}

void focusOutEvent ( QFocusEvent * event ) { 
                   resize(originalWidth,originalHeight); 
                   QToolButton::focusOutEvent(event);
}

2 个答案:

答案 0 :(得分:3)

你应该做这样的事情

class YourButton : public QToolButton
{
    Q_OBJECT

    protected:

    void focusInEvent(QFocusEvent* e);
    void focusOutEvent(QFocusEvent* e);
};

在.cpp文件中

void YourButton::focusInEvent(QFocusEvent* e)
{
    if (e->reason() == Qt::MouseFocusReason)
    {
      // Resize the geometry -> resize(bigWidth,bigHeight); 
    }


    QToolButton::focusInEvent(e);
}

然后在mainWindow中使用yourButton类。

另外(另一个选项)您可以在mainWindow中使用http://qt-project.org/doc/qt-4.8/qobject.html#installEventFilter

答案 1 :(得分:1)

@Wagmare的解决方案仅适用于布局之外的按钮。 为了使它在布局内工作,它应该如下所示:

class YourButton : public QToolButton
{
    Q_OBJECT
    // proper constructor and other standard stuff 
    // ..

protected:
    void focusInEvent(QFocusEvent* e) {
        QToolButton::focusInEvent(e);
        updateGeometry();
    }

    void focusOutEvent(QFocusEvent* e) {
        QToolButton::focusOutEvent(e);
        updateGeometry();
    }


public:
    QSize sizeHint() const {
        QSize result = QToolButton::sizeHint();
        if (hasFocuc()) {
            result += QSize(20,20);
        }
        return result;
    }
};

使用适当的大小政策,它也可以在没有布局的情况下工作。

<小时/> 没有子类化的另一个很酷的解决方案是样式表:

QPushButton:focus {
    min-height: 40px
    min-width:  72px
}