简体   繁体   English

Qt Group菜单动作一起

[英]Qt Group menu actions together

I have some QMenu objects that share some QAction 's between them and toolbars. 我有一些QMenu对象,它们在它们和工具栏之间共享一些QAction

The detail here is that I want to reproduce some menu parts over other menus. 这里的细节是我想在其他菜单上重现一些菜单部分。 For instance, in my QMainWindow object's MenuBar, I have something like 例如,在我的QMainWindow对象的MenuBar中,我有类似

File
  (x) New
  (x) Open
  (x) Save
  (x) ------
  (x) Add Sketch...
  (-) Export...
  (-) Import...

And then, in some context menu, I want to reproduce the same exact structure with only the actions marked with (x) , using the same action objects. 然后,在某些上下文菜单中,我想使用相同的动作对象,仅使用标记为(x)的动作来再现相同的确切结构。 I want to do this over several menus. 我想通过几个菜单来做到这一点。

The naive approach is to repeat the same code when building the QMainWindow menu and the context menu that repeats the structure. 天真的方法是在构建QMainWindow菜单和重复该结构的上下文菜单时重复相同的代码。 But this means repeating code and therefore doubling the maintenance effort (times the number of repeated menu actions). 但这意味着重复代码,因此使维护工作加倍(乘以重复菜单操作的次数)。

Is there a direct approach of solving this on Qt? 在Qt上有解决此问题的直接方法吗?

One option can be to have the actions stored in a dictionary, and then save different lists of keys for each submenu. 一种选择是将操作存储在字典中,然后为每个子菜单保存不同的键列表。 All you have to do later is just to build the menu using a simple for. 您以后要做的只是使用简单的for来构建菜单。 A draft code may look like: 草稿代码可能如下所示:

QMap<QString, QAction*> actions;
actions["new"] = new QAction(...); // connect, etc.
actions["-"] = new QAction(...); // for separator

QMap<QString, QStringList> menus;
menus["file"] << "new" << "save" << ... << "import" << ...;
menus["context1"] << "new" << "save" << ...;

QMenu* buildMenu(const QString& name) {
  if (!menus.contains(name)) return nullptr;
  auto menu = new QMenu();
  Q_FOREACH (const auto& entry, menus[name]) {
    menu->addAction(actions[entry]);
  }
  return menu;
}

Finally, make actions and menus available to buildMenu (a class, anonymous namespace together some initialisation...). 最后,使actionsmenus可用于buildMenu (一个类,匿名名称空间以及一些初始化...)。 Also remember to delete the returned menu after using it. 还记得使用后删除返回的菜单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM