我正在实现一个应用程序,其中我有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);
}
发布于 2014-01-16 15:08:37
你应该这样做
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。
发布于 2014-01-16 18:25:54
@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
}
https://stackoverflow.com/questions/21155148
复制相似问题