pyqt5 菜单栏单选
时间: 2023-08-21 08:02:23 浏览: 168
在PyQt5中,可以使用QActionGroup类来实现菜单栏的单选功能。下面是一个示例代码:
```python
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, QMenu, QActionGroup
import sys
class MenuBarDemo(QMainWindow):
def __init__(self):
super(MenuBarDemo, self).__init__()
bar = self.menuBar()
file = bar.addMenu("选择")
group = QActionGroup(self)
action1 = QAction("选项1", self)
action1.setCheckable(True)
action1.setChecked(True)
action1.triggered.connect(self.actionTriggered)
action2 = QAction("选项2", self)
action2.setCheckable(True)
action2.triggered.connect(self.actionTriggered)
action3 = QAction("选项3", self)
action3.setCheckable(True)
action3.triggered.connect(self.actionTriggered)
group.addAction(action1)
group.addAction(action2)
group.addAction(action3)
file.addAction(action1)
file.addAction(action2)
file.addAction(action3)
def actionTriggered(self):
action = self.sender()
print("选中了:", action.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWin = MenuBarDemo()
mainWin.show()
sys.exit(app.exec_())
```
在这个示例中,我们创建了一个菜单栏,并向其添加了一个"选择"的菜单项。然后,我们创建了一个QActionGroup对象,用于管理菜单项的单选功能。
接着,我们创建了三个QAction对象,并将它们添加到QActionGroup中。然后,我们将这些QAction对象添加到"选择"菜单中。
当用户选中某个菜单项时,会触发actionTriggered槽函数,并打印出选中的菜单项的文本。
这样,我们就实现了菜单栏的单选功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [【pyqt5学习】——菜单栏(QMenu())、工具栏QToolBar学习](https://blog.csdn.net/qq_45769063/article/details/124992097)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [PyQt5学习(一):布局管理+信号和槽关联+菜单栏与工具栏+打包资源包](https://blog.csdn.net/qq_45802081/article/details/117534692)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文