2015-11-06 103 views
-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_()) 

回答

1

有你需要做一些修改,但你可以通過禁用QAction做到這一點。

第一次更改,使您的editItem變量在整個班級都可以訪問。

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)) 

例子:

只有一個項目中選擇:

One item selected

隨着多個項目的選擇:

More than one item selected