2016-12-24 31 views
0

我正在使用PySide編程GUI。我目前有用戶選擇一個包含許多數據文件的目錄。我將這些文件名加載到列表中。我希望GUI顯示一個彈出式菜單,顯示文件名列表,允許用戶選擇一個,多個或全部文件繼續。現在我正在使用,PySide彈出顯示列表和多個選擇

items, ok = QInputDialog.getItem(self, "Select files", "List of files", datafiles, 0, False) 

這隻允許用戶選擇一個文件,而不是多個。我如何向用戶顯示項目列表並讓他們突出顯示他們想要的數量,然後返回列表?

謝謝!

+0

的QInputDialog類提供了一個簡單方便的對話框,獲得一個單** **價值來自用戶。 – eyllanesc

回答

0

QInputDialog類提供了一個簡單的便利對話框來獲取用戶的值單值,但我們可以創建自定義對話框。

import sys 

from PySide.QtCore import Qt 
from PySide.QtGui import QApplication, QDialog, QDialogButtonBox, QFormLayout, \ 
    QLabel, QListView, QPushButton, QStandardItem, QStandardItemModel, QWidget 


class MyDialog(QDialog): 
    def __init__(self, title, message, items, parent=None): 
     super(MyDialog, self).__init__(parent=parent) 
     form = QFormLayout(self) 
     form.addRow(QLabel(message)) 
     self.listView = QListView(self) 
     form.addRow(self.listView) 
     model = QStandardItemModel(self.listView) 
     self.setWindowTitle(title) 
     for item in items: 
      # create an item with a caption 
      standardItem = QStandardItem(item) 
      standardItem.setCheckable(True) 
      model.appendRow(standardItem) 
     self.listView.setModel(model) 

     buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) 
     form.addRow(buttonBox) 
     buttonBox.accepted.connect(self.accept) 
     buttonBox.rejected.connect(self.reject) 

    def itemsSelected(self): 
     selected = [] 
     model = self.listView.model() 
     i = 0 
     while model.item(i): 
      if model.item(i).checkState(): 
       selected.append(model.item(i).text()) 
      i += 1 
     return selected 


class Widget(QWidget): 
    def __init__(self, parent=None): 
     super(Widget, self).__init__(parent=parent) 
     self.btn = QPushButton('Select', self) 
     self.btn.move(20, 20) 
     self.btn.clicked.connect(self.showDialog) 
     self.setGeometry(300, 300, 290, 150) 
     self.setWindowTitle('Input dialog') 

    def showDialog(self): 
     items = [str(x) for x in range(10)] 
     dial = MyDialog("Select files", "List of files", items, self) 
     if dial.exec_() == QDialog.Accepted: 
      print(dial.itemsSelected()) 

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    ex = Widget() 
    ex.show() 
    sys.exit(app.exec_()) 

enter image description here

點擊按鈕後:

enter image description here

輸出:

['1', '2', '4', '5'] 
+0

太棒了!這正是我所尋找的,非常感謝:) – user1408329