做艺术品的网站,购物网站功能设计,wordpress主题文制作,如何把网站建设好1、概述
QMenu是Qt框架中的一个类#xff0c;用于创建和管理菜单。它提供了丰富的接口来添加菜单项#xff08;通常是QAction对象#xff09;、子菜单以及分隔符。QMenu可以嵌入到菜单栏#xff08;QMenuBar#xff09;中#xff0c;也可以作为弹出菜单#xff08;通过…1、概述
QMenu是Qt框架中的一个类用于创建和管理菜单。它提供了丰富的接口来添加菜单项通常是QAction对象、子菜单以及分隔符。QMenu可以嵌入到菜单栏QMenuBar中也可以作为弹出菜单通过调用exec()方法使用。QMenu支持嵌套菜单即菜单项本身可以是一个子菜单从而创建出复杂的菜单结构。
QMenu不仅支持文本菜单项还支持图标、快捷键和状态提示等功能这些都可以通过QAction来设置。此外QMenu还提供了对菜单项可见性、启用/禁用状态以及检查状态checkable的细粒度控制。 2、重要方法
addAction(QAction *action)向菜单中添加一个动作。addMenu(QMenu *menu)向菜单中添加一个子菜单。addSeparator()在菜单中添加一个分隔符。clear()清除菜单中的所有项。exec(const QPoint pos QPoint())在指定位置显示菜单作为弹出菜单并返回用户选择的动作的索引或-1如果没有选择。setDefaultAction(QAction *action)设置菜单的默认动作当用户按下回车键时触发。setTitle(const QString title)设置菜单的标题。actions()返回菜单中所有动作的列表。 3、重要信号
triggered(QAction *action)当菜单中的某个动作被触发时发出此信号。aboutToShow()在菜单即将显示之前发出此信号可以用于动态调整菜单项。aboutToHide()在菜单即将隐藏之前发出此信号。
需要注意的是QMenu本身并不直接处理用户输入而是通过QAction来响应动作。因此大多数与QMenu交互的信号和槽都是通过QAction来实现的。
#include QApplication
#include QMainWindow
#include QMenuBar
#include QMenu
#include QAction
#include QMessageBox class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent nullptr) : QMainWindow(parent) { // 创建菜单栏 QMenuBar *menuBar this-menuBar(); // 创建文件菜单 QMenu *fileMenu menuBar-addMenu(tr(File)); // 创建动作 QAction *newAction new QAction(tr(New), this); newAction-setIcon(QIcon(:/icons/new.png)); newAction-setStatusTip(tr(Create a new file)); connect(newAction, QAction::triggered, this, MainWindow::onNewFile); QAction *openAction new QAction(tr(Open...), this); openAction-setIcon(QIcon(:/icons/open.png)); openAction-setStatusTip(tr(Open an existing file)); connect(openAction, QAction::triggered, this, MainWindow::onOpenFile); // 将动作添加到文件菜单 fileMenu-addAction(newAction); fileMenu-addAction(openAction); // 创建一个弹出菜单 QMenu *popupMenu new QMenu(this); QAction *exitAction new QAction(tr(Exit), this); exitAction-setStatusTip(tr(Exit the application)); connect(exitAction, QAction::triggered, qApp, QApplication::quit); popupMenu-addAction(exitAction); QPushButton *btn new QPushButton(this);setCentralWidget(btn);connect(btn, QPushButton::clicked, this, [, btn, popupMenu]{popupMenu-exec(btn-mapToGlobal(btn-rect().center()));});} private slots: void onNewFile() { QMessageBox::information(this, tr(New File), tr(Create a new file...)); } void onOpenFile() { QMessageBox::information(this, tr(Open File), tr(Open an existing file...)); }
}; int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow window; window.show(); return app.exec();
} 觉得有帮助的话打赏一下呗。。