在PySide中使用QMenu
,我想根据QListWidget
选择计数禁用菜单项。如果选择计数恰好是一个,则编辑项目'应该启用操作,否则应该禁用它。我怎么能这样做?
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Modules
# ------------------------------------------------------------------------------
import sys
from PySide import QtGui, QtCore
# Variables
# ------------------------------------------------------------------------------
listItems = ["A","B","C","D","E","F","G"]
# widget
# ------------------------------------------------------------------------------
class Example(QtGui.QWidget):
def __init__(self,):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.setGeometry(300, 300, 250, 300)
self.setWindowTitle("Input List")
# widgets
self.itemList = QtGui.QListWidget()
self.itemList.addItems(listItems)
self.itemList.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
# context menu
self.edit_menu = QtGui.QMenu()
removeItem = self.edit_menu.addAction('Remove Item')
removeItem.triggered.connect(self.RemoveItem)
editItem = self.edit_menu.addAction('Edit Item')
editItem.triggered.connect(self.EditItem)
self.itemList.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.itemList.customContextMenuRequested.connect(self.on_context_menu)
self.itemList.itemDoubleClicked.connect(self.EditItem)
# layout
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.addWidget(self.itemList, 0, 0)
self.show()
def on_context_menu(self, pos):
self.edit_menu.exec_(self.mapToGlobal(pos))
def EditItem(self):
print "Edit Item"
def RemoveItem(self):
print "Remove Item"
# Main
# ------------------------------------------------------------------------------
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
答案 0 :(得分:1)
您需要进行一些更改,但可以通过禁用QAction
来执行此操作。
首先进行更改,让您的self.editItem = self.edit_menu.addAction('Edit Item')
self.editItem.triggered.connect(self.EditItem)
变量在整个课程中都可访问。
remoteItem
(为了保持一致性,您可能也想对on_context_menu
执行此操作)
接下来,在def on_context_menu(self, pos):
if len(self.itemList.selectedItems()) == 1:
self.editItem.setEnabled(False)
else:
self.editItem.setEnabled(True)
self.edit_menu.exec_(self.mapToGlobal(pos))
中,您需要检查已选择的项目数。然后根据该逻辑启用/禁用菜单选项:
Form::model
示例:
只选择了一个项目:
选择了多个项目: