qt QToolBar如何从最右侧开始添加QAction?
时间: 2023-12-24 18:06:13 浏览: 447
可以使用QToolBar的addActions()函数将多个QAction同时添加到工具栏中,然后使用setToolButtonStyle()函数将工具栏的显示方式设置为Qt::ToolButtonFollowStyle,这样工具栏上的按钮就会自动填充整个工具栏,并且从最右侧开始添加QAction。示例代码如下:
```cpp
QToolBar *toolBar = new QToolBar(this);
toolBar->setWindowTitle("My ToolBar");
// 添加要插入的QAction
QAction *action1 = new QAction("Action 1", this);
QAction *action2 = new QAction("Action 2", this);
QAction *action3 = new QAction("Action 3", this);
// 将多个QAction添加到工具栏中
toolBar->addActions({action1, action2, action3});
// 将工具栏的显示方式设置为Qt::ToolButtonFollowStyle
toolBar->setToolButtonStyle(Qt::ToolButtonFollowStyle);
```
这样就可以从最右侧开始添加QAction了。
相关问题
qt QToolBar从右添加QAction
您可以使用 `QToolBar` 的 `insertAction()` 函数将 `QAction` 从右侧添加到工具栏中。以下是一个示例:
```cpp
QToolBar *toolBar = new QToolBar(this);
QAction *action = new QAction(QIcon("icon.png"), "Action", this);
toolBar->insertAction(nullptr, action); // 添加到最右侧
```
在上面的示例中,`insertAction()` 函数的第一个参数是 `nullptr`,表示将 `QAction` 添加到工具栏的最右侧。您还可以将其替换为其他 `QAction`,以指定新 `QAction` 的插入位置。
qt 设置QToolBar的下拉菜单靠近右侧
可以使用QToolBar的addSeparator方法在右侧添加分隔符,这样下拉菜单将会靠近右侧。
具体实现代码如下:
```cpp
QToolBar *toolBar = new QToolBar(this);
// 添加工具按钮
QAction *action1 = toolBar->addAction(QIcon(":/images/open.png"), "打开");
QAction *action2 = toolBar->addAction(QIcon(":/images/save.png"), "保存");
QAction *action3 = toolBar->addAction(QIcon(":/images/exit.png"), "退出");
// 在右侧添加分隔符
QWidget *spacer = new QWidget(this);
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
toolBar->addWidget(spacer);
// 添加下拉菜单
QMenu *menu = new QMenu(this);
menu->addAction("菜单项1");
menu->addAction("菜单项2");
menu->addAction("菜单项3");
QToolButton *button = new QToolButton(this);
button->setText("下拉菜单");
button->setPopupMode(QToolButton::InstantPopup);
button->setMenu(menu);
toolBar->addWidget(button);
```
这里使用了一个QWidget控件作为分隔符,设置了其大小策略为Expanding,可以自动填充空间,使得分隔符在右侧。然后再往QToolBar中添加下拉菜单即可。
阅读全文