【发布时间】:2020-04-29 02:24:44
【问题描述】:
我是 QML、QtQuick 和 Python 的新手。我想使用 QML 显示文件列表(完整路径)。看来我应该使用 ListView 和 ListElements。我发现的示例和教程都使用硬编码且非常简单的列表数据。我不明白如何从这些例子变成更现实的东西。
如何使用后端的 Python 字符串数组填充 QML UI 显示的列表?
字符串数组的长度是任意的。我希望列表项是可点击的(可能是 QML url 类型)。他们将为该文件/url 类型打开操作系统的默认应用程序。
我的后端代码是这样的:
import sys
from subprocess import Popen, PIPE
import getpass
from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtCore import Qt, QCoreApplication, QObject, pyqtSlot
from PyQt5.QtQml import QQmlApplicationEngine
class Backend(QObject):
basepath = '/path/to/files'
list_files_cmd = "find " + basepath + " -type f -readable"
myfiles = Popen(list_files_cmd, shell=True, stdout=PIPE, stderr=PIPE)
output, err = myfiles.communicate()
# the output is a Byte literal like this: b'/path/to/file1.txt\n/path/to/file2.txt\n'. Transform into a regular string:
newstr = output.decode(encoding='UTF-8')
files_list = newstr.split('\n')
for file in files_list:
print(file)
if __name__ == '__main__':
backend = Backend()
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
app = QApplication(sys.argv)
engine = QQmlApplicationEngine('view.qml')
engine.rootContext().setContextProperty("backend", backend)
sys.exit(app.exec_())
现在我只是将 files_list 字符串数组从后端打印到控制台,但目标是使用该字符串数组来填充 UI 中的 QML 列表。
files_list 的内容示例如下:
['/path/to/files/xdgr/todo.txt', '/path/to/files/xdgr/a2hosting.txt', '/path/to/files/xdgr/paypal.txt', '/path/to/files/xdgr/toggle.txt', '/path/to/files/xdgr/from_kty.txt', '/path/to/files/xdgr/feed59.txt', '/path/to/files/one/sharing.txt', '/path/to/files/two/data.dbx', '']
(我需要弄清楚如何处理该数组末尾的空字符串。)
我的 QML 的大致轮廓(在我目前的能力范围内)是这样的:
import QtQml.Models 2.2
import QtQuick.Window 2.2
import QtQuick 2.2
import QtQuick.Controls 1.3
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
TabView {
anchors.fill: parent
Tab {
title: "Files"
anchors.fill: parent
ListView {
id: mListViewId
anchors.fill: parent
model: mListModelId
delegate : delegateId
}
ListModel {
id: mListModelId
// I would like backend.files_list to provide the model data
}
}
}
Component.onCompleted: {
mListModelId.append(backend.files_list)
}
}
我发现的最相关的问题是这些,但它们并没有解决我的问题:
qt - 动态创建 QML ListElement 和内容 - 码客Dynamically create QML ListElement and content
qt - QML ListElement 传递字符串列表 - 码客QML ListElement pass list of strings
【问题讨论】:
-
查看 QStringlistModel,ListModel 不适合这里
-
Python 有类似的东西吗? bogotobogo.com/Qt/…
-
@FrankOsterfeld QStringlistModel 似乎是一个 C++ 类。我正在使用 Python。
-
@MountainX-for-Monica PyQt5 和 PySide2 是 Qt5 的绑定,因此大多数 C++ 类都存在于 python 中。
标签: python pyqt qml pyqt5 qtquick2