qt dialog创建菜单
时间: 2023-10-26 16:06:20 浏览: 49
在 Qt 中,可以使用 QMenu 和 QAction 类来创建菜单。
首先,创建一个 QMenu 对象,并使用 addMenu() 方法将它添加到 QMainWindow 或 QDialog 中。然后,使用 addAction() 方法创建 QAction 对象,并将它添加到 QMenu 中。
下面是一个简单的例子,在 QDialog 中创建一个菜单:
```cpp
#include <QDialog>
#include <QMenu>
#include <QMenuBar>
class MyDialog : public QDialog {
public:
MyDialog(QWidget *parent = nullptr) : QDialog(parent) {
// 创建菜单栏
QMenuBar *menuBar = new QMenuBar(this);
setMenuBar(menuBar);
// 创建菜单
QMenu *fileMenu = new QMenu("File", this);
menuBar->addMenu(fileMenu);
// 创建动作
QAction *newAction = new QAction("New", this);
fileMenu->addAction(newAction);
QAction *openAction = new QAction("Open", this);
fileMenu->addAction(openAction);
QAction *exitAction = new QAction("Exit", this);
fileMenu->addAction(exitAction);
// 连接动作的槽函数
connect(newAction, &QAction::triggered, this, &MyDialog::onNew);
connect(openAction, &QAction::triggered, this, &MyDialog::onOpen);
connect(exitAction, &QAction::triggered, this, &MyDialog::onExit);
}
private slots:
void onNew() {
// 处理 New 动作
}
void onOpen() {
// 处理 Open 动作
}
void onExit() {
// 处理 Exit 动作
close();
}
};
```
在此例中,我们创建了一个名为 "File" 的菜单,并添加了三个 QAction,分别是 "New"、"Open" 和 "Exit"。然后,我们将这些 QAction 连接到 MyDialog 的槽函数中,以便处理它们的触发事件。
注意,我们使用了 connect() 方法来连接 QAction 的 triggered 信号和 MyDialog 的槽函数。当 QAction 被触发时,它会发出 triggered 信号,然后 MyDialog 会调用相应的槽函数来处理它。