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_())
點擊按鈕後:
輸出:
['1', '2', '4', '5']
的QInputDialog類提供了一個簡單方便的對話框,獲得一個單** **價值來自用戶。 – eyllanesc