显示列表和多个

2024-06-01 05:56:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用PySide编写一个GUI。我现在让用户选择一个目录,其中有许多数据文件。我把这些文件名加载到一个列表中。我希望图形用户界面显示一个弹出式菜单,显示文件名列表,允许用户选择一个、多个或所有文件来继续。现在我正在使用

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

这只允许用户选择一个文件,而不是多个。我如何向用户显示一个项目列表,并让他们高亮显示所需数量,然后返回列表?在

谢谢!在


Tags: 文件用户目录列表文件名数据文件菜单items
1条回答
网友
1楼 · 发布于 2024-06-01 05:56:50

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

输出:

^{pr2}$

相关问题 更多 >