-1
在PySide中使用QMenu
,我想根據QListWidget
選擇計數禁用菜單項。如果選擇計數恰好爲1,則應啓用「編輯項目」操作,否則應禁用它。我怎樣才能做到這一點?禁用菜單項,除非PySide只選擇一個項目
#!/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_())