gpt4 book ai didi

c++ - 如何使用 Qt 聚焦 menuBar()

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:19:54 28 4
gpt4 key购买 nike

我有一个工作应用程序。我在带有一些菜单的主窗口中添加了一个 menuBar()。然后,我将其隐藏以释放屏幕空间。我写了下面的代码,这样当用户按下 ALT 键时,菜单栏在隐藏时出现,在显示时隐藏。

void MainWindow::keyPressEvent( QKeyEvent *k ) {
if(k->modifiers() & Qt::AltModifier) {
menuBar()->setHidden(!menuBar()->isHidden());
if(menuBar()->hasFocus()) {
QMessageBox::information(this, "Info", "Focus !");
}
}
}

如您所见,我还添加了一个 QMessageBox 以查看 menuBar 何时获得焦点。而这个框只出现了一半的时间。它是这样的:

  1. 应用程序已启动,菜单栏已隐藏
  2. 我按下 ALT,显示菜单栏,没有消息框,没有焦点
  3. 我按下 ALT,隐藏了菜单栏
  4. 我按下 ALT,显示菜单栏,消息框,焦点
  5. 我按下 ALT,隐藏了菜单栏
  6. 我按下 ALT,显示菜单栏,没有消息框,没有焦点
  7. 我按下 ALT,隐藏了菜单栏
  8. 我按下 ALT,显示菜单栏,消息框,焦点
  9. 等等

如何确保在显示 menuBar 时,它始终具有焦点?

最佳答案

我也想做同样的事情。我的解决方案,完整示例,作为要点:

https://gist.github.com/xim/ee56564f425151ea2fa70f730d644873

针对 Qt 5.9.4 进行了测试。

因为它包含很多其他垃圾,一个最小的例子:

class AutoHidingMenuBar : public QMenuBar {
Q_OBJECT

public:
AutoHidingMenuBar() : QMenuBar() {
setMaximumHeight(0);
connect(qApp, &QApplication::focusChanged, this, &AutoHidingMenuBar::focusChanged);
}

private slots:
void focusChanged(QWidget *from, QWidget *to) {
bool inFocus = hasFocus() || isAncestorOf(focus) || hasFocusedChild();
if (inFocus && maximumHeight() == 0) {
auto action = activeAction();
setMaximumHeight(100);
if (action) {
// XXX This is a bit of a hack. We could do
// QCoreApplication::processEvents();
// setActiveAction(action);
// with almost the same effect, but then we *open* the first menu on single alt press...
auto evt = new QMouseEvent(QEvent::MouseMove, actionGeometry(action).center(), Qt::NoButton, Qt::NoButton, Qt::NoModifier);
QCoreApplication::postEvent(this, evt);
}
} else if (!inFocus && maximumHeight() != 0)) {
setMaximumHeight(0);
}
}

private:
bool hasFocusedChild() {
QObjectList queue{children()};
while (!queue.empty()) {
auto child = queue.takeFirst();
auto widget = dynamic_cast<QWidget *>(child);
if (widget && widget->hasFocus())
return true;

queue.append(child->children());
}
return false;
}
};

关于c++ - 如何使用 Qt 聚焦 menuBar(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27928937/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com