2

我正在实现一个应用程序,其中我有 3QToolButton并且当焦点出现在任何QToolButton它应该的时候resize。我的一位朋友给了我答案,但我无法弄清楚,因为我QMainWindow也在我的 mainWindow 中继承类。他也说要继承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);

};

我的窗口.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);
}
4

2 回答 2

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);
}

然后在主窗口中使用 yourButton 类。

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

于 2014-01-16T07:08:37.370 回答
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
}
于 2014-01-16T10:25:54.373 回答