PySide2/QML 填充 Gridview 模型/委托并为其设置动画

2024-05-06

我是 QML 的新手,正在寻求以下几点帮助

  • 如何基于 TextField 输入(如 Regex )通过 PySide2 过滤 Gridview 模型中的 QAbstractListModel 数据(标题)。

  • 如何在鼠标悬停时为 Gridview 的委托设置动画(如下图所示。)

这是测试代码

qmlHoverView.py

from PySide2 import QtCore, QtQuick, QtGui, QtWidgets, QtQml
import os
import sys

class inventoryModel(QtCore.QAbstractListModel):
    def __init__(self, entries, parent=None):
        super(inventoryModel, self).__init__(parent)
        self.titleRole = QtCore.Qt.UserRole + 1000
        self.thumbnailRole = QtCore.Qt.UserRole + 1001
        self._entries = entries

    def rowCount(self, parent=QtCore.QModelIndex()):
        if parent.isValid(): return 0
        return len(self._entries)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if 0 <= index.row() < self.rowCount() and index.isValid():
            item = self._entries[index.row()]
            if role == self.titleRole:
                return item["title"]
            elif role == self.thumbnailRole:
                return item["thumbnail"]

    def roleNames(self):
        roles = dict()
        roles[self.titleRole] = b"title"
        roles[self.thumbnailRole] = b"thumbnail"
        return roles

    def appendRow(self, n, t):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self._entries.append(dict(name=n, type=t))
        self.endInsertRows()



class Foo(QtCore.QObject):
    def __init__(self):
        QtCore.QObject.__init__(self)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    entries = [
        {"title": "Zero", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/zero.png"},
        {"title": "One", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/one.png"},
        {"title": "Two", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/two.png"},
        {"title": "Three", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/three.png"},
        {"title": "Four", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/four.png"},
        {"title": "Five", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/five.png"},
        {"title": "Six", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/six.png"},
        {"title": "Seven", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/seven.png"},
        {"title": "Eight", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/eight.png"},
        {"title": "Nine", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/nine.png"},
    ]
    assetModel = inventoryModel(entries)
    foo = Foo()
    engine = QtQml.QQmlApplicationEngine()
    engine.rootContext().setContextProperty("foo", foo)
    engine.rootContext().setContextProperty("assetModel", assetModel)
    engine.load(QtCore.QUrl.fromLocalFile('E:/Tech/QML/projects/Test_005/main.qml'))
    if not engine.rootObjects():
        sys.exit(-1)
    engine.quit.connect(app.quit)
    sys.exit(app.exec_())

main.qml

import QtQuick 2.13
import QtQuick.Controls 2.13
import QtQuick.Layouts 1.13

ApplicationWindow {
    id: mainWindowId
    visible: true
    width: 1280
    height: 720
    title: qsTr("Image Hover Effect")

    Rectangle {
        width: parent.width
        height: parent.height

        ColumnLayout {
            width: parent.width
            height: parent.height
            spacing: 0

            TextField{
                id: filterTextFieldId
                Layout.fillWidth: true
                Layout.preferredHeight: 40
                font {
                    family: "SF Pro Display"
                    pixelSize: 22
                }

                color: "dodgerblue"
            }

            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                color: "gold"

                GridView {
                    id: thumbViewId
                    width: parent.width
                    height: parent.height
                    anchors.fill: parent
                    anchors.margins: 25
                    cellWidth: 260
                    cellHeight: 260
                    model: assetModel
                    delegate: ThumbDelegate {}
                    focus: true
                }
            }
        }
    }

    Connections {
        target: foo
    }
}

ThumbDelegate.qml

import QtQuick 2.13
import QtQuick.Controls 2.13
import QtQuick.Layouts 1.13

Component {
    Rectangle {
        width: 256
        height: 256
        color: 'green'

        Image {
            id: thumbImageId
            source: thumbnail
            asynchronous: true
        }

        Rectangle {
            width: parent.width
            height: 50
            anchors.bottom: parent.bottom
            color: 'grey'

            Label {
                anchors.verticalCenter: parent.verticalCenter
                anchors.left: parent.left
                anchors.leftMargin: 10
                text: title
                font.family: 'SF Pro Display'
                font.pixelSize: 22
                color: 'white'
            }
        }
    }
}

上述代码的输出


您提出了不同的问题,这次我将回答所有问题,但下次您将必须按照 SO 指南中的指示为每个问题创建一个帖子。


在您的情况下,需要 3 个元素:

  • 将图像加载到 GridView 中:建议实现一个模型,在本例中,基于具有自定义角色的 QStandardItemModel 实现它,并与委托建立连接。

  • Filter:为此,您可以使用 DelegateModel 或 QSortFilterProxyModel,在本例中使用第二个选项,因为它按角色并通过正则表达式实现过滤。

  • 悬停动画:首先是检测鼠标何时进入或退出项目,为此使用 MouseArea 来触发进入和退出信号。然后我们使用Behavior来设置“y”属性改变时的动画。然后只需要在信号被触发时设置各自的最终值即可。我已删除“anchors.bottom:parent.bottom”,因为锚点不允许修改属性。

另一方面,如果您为委托创建 qml,则无需使用 Component,因为它本身就是一个组件,另一方面,您必须启用“clip”属性,以便项目的绘制不会超出其范围。自己的区域。

综合以上情况,解决方案是:

├── images
│   └── android.png
├── main.py
└── qml
    ├── main.qml
    └── ThumbDelegate.qml

main.py

import os
import sys

from PySide2 import QtCore, QtGui, QtWidgets, QtQml


class CustomModel(QtGui.QStandardItemModel):
    TitleRole = QtCore.Qt.UserRole + 1000
    UrlRole = QtCore.Qt.UserRole + 1001

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setItemRoleNames(
            {CustomModel.TitleRole: b"title", CustomModel.UrlRole: b"thumbnail"}
        )

    @QtCore.Slot(str, QtCore.QUrl)
    def addItem(self, title, url):
        it = QtGui.QStandardItem()
        it.setData(title, CustomModel.TitleRole)
        it.setData(url, CustomModel.UrlRole)
        self.appendRow(it)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    current_dir = os.path.dirname(os.path.realpath(__file__))

    model = CustomModel()

    # add items
    for (
        text
    ) in "amputate arena accept architecture astonishing advertise abortion apple absolute advice".split():
        title = text
        image_path = os.path.join(current_dir, "images", "android.png")
        model.addItem(title, QtCore.QUrl.fromLocalFile(image_path))

    proxy_filter = QtCore.QSortFilterProxyModel()
    proxy_filter.setSourceModel(model)
    proxy_filter.setFilterRole(CustomModel.TitleRole)

    engine = QtQml.QQmlApplicationEngine()

    engine.rootContext().setContextProperty("proxy_filter", proxy_filter)
    filename = os.path.join(current_dir, "qml", "main.qml")
    engine.load(QtCore.QUrl.fromLocalFile(filename))

    if not engine.rootObjects():
        sys.exit(-1)
    engine.quit.connect(app.quit)
    sys.exit(app.exec_())

main.qml

import QtQuick 2.13
import QtQuick.Controls 2.13
import QtQuick.Layouts 1.13

ApplicationWindow {
    id: mainWindowId
    visible: true
    width: 1280
    height: 720
    title: qsTr("Image Hover Effect")

    Rectangle {
        anchors.fill: parent

        ColumnLayout {
            anchors.fill: parent
            spacing: 0
            TextField{
                id: filterTextFieldId
                Layout.fillWidth: true
                Layout.preferredHeight: 40
                font {
                    family: "SF Pro Display"
                    pixelSize: 22
                }
                color: "dodgerblue"
                onTextChanged: proxy_filter.setFilterRegExp(text)
            }

            Rectangle {
                Layout.fillWidth: true
                Layout.fillHeight: true
                color: "gold"
                GridView {
                    clip: true
                    id: thumbViewId
                    anchors.fill: parent
                    anchors.margins: 25

                    cellWidth: 260
                    cellHeight: 260

                    model: proxy_filter
                    delegate: ThumbDelegate {
                        source: model.thumbnail
                        title: model.title
                    }
                    focus: true
                }
            }
        }
    }
}

ThumbDelegate.qml

import QtQuick 2.13
import QtQuick.Controls 2.13
import QtQuick.Layouts 1.13


Rectangle {
    id: root
    width: 256
    height: 256
    color: 'green'
    clip: true

    property alias source: thumbImageId.source
    property alias title: label.text

    Image {
        id: thumbImageId
        asynchronous: true
        anchors.fill: parent
    }

    Rectangle {
        id: base
        width: parent.width
        height: 50
        color: 'grey'
        y: root.height
        Behavior on y { NumberAnimation {duration: 500} }
        Label {
            id: label
            anchors.verticalCenter: parent.verticalCenter
            anchors.left: parent.left
            anchors.leftMargin: 10
            font.family: 'SF Pro Display'
            font.pointSize: 22
            color: 'white'
        }
    }


    MouseArea{
        anchors.fill: parent
        hoverEnabled: true
        onEntered: base.y = root.height - base.height
        onExited: base.y = root.height
    }
}

Update:

看到你已经更新了你的问题,只需要修改python代码,qml代码必须与我在上一部分答案中提出的相同。

*.py

import os
import sys

from PySide2 import QtCore, QtGui, QtWidgets, QtQml


class InventoryModel(QtCore.QAbstractListModel):
    TitleRole = QtCore.Qt.UserRole + 1000
    ThumbnailRole = QtCore.Qt.UserRole + 1001

    def __init__(self, entries, parent=None):
        super().__init__(parent)
        self._entries = entries

    def rowCount(self, parent=QtCore.QModelIndex()):
        return 0 if parent.isValid() else len(self._entries)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if 0 <= index.row() < self.rowCount() and index.isValid():
            item = self._entries[index.row()]
            if role == InventoryModel.TitleRole:
                return item["title"]
            elif role == InventoryModel.ThumbnailRole:
                return item["thumbnail"]

    def roleNames(self):
        roles = dict()
        roles[InventoryModel.TitleRole] = b"title"
        roles[InventoryModel.ThumbnailRole] = b"thumbnail"
        return roles

    def appendRow(self, n, t):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self._entries.append(dict(title=n, thumbnail=t))
        self.endInsertRows()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    current_dir = os.path.dirname(os.path.realpath(__file__))

    entries = [
        {"title": "Zero", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/zero.png"},
        {"title": "One", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/one.png"},
        {"title": "Two", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/two.png"},
        {"title": "Three", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/three.png"},
        {"title": "Four", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/four.png"},
        {"title": "Five", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/five.png"},
        {"title": "Six", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/six.png"},
        {"title": "Seven", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/seven.png"},
        {"title": "Eight", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/eight.png"},
        {"title": "Nine", "thumbnail": "file:///E:/Tech/QML/projects/Test_005/nine.png"},
    ]

    assetModel = InventoryModel(entries)
    engine = QtQml.QQmlApplicationEngine()

    proxy_filter = QtCore.QSortFilterProxyModel()
    proxy_filter.setSourceModel(assetModel)
    proxy_filter.setFilterRole(InventoryModel.TitleRole)

    engine.rootContext().setContextProperty("proxy_filter", proxy_filter)
    engine.load(QtCore.QUrl.fromLocalFile('E:/Tech/QML/projects/Test_005/main.qml'))

    if not engine.rootObjects():
        sys.exit(-1)

    engine.quit.connect(app.quit)
    sys.exit(app.exec_())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PySide2/QML 填充 Gridview 模型/委托并为其设置动画 的相关文章

随机推荐

  • 用户输入时的空闲时间

    我遇到的问题是一个搜索函数 它应该调用我的doSearch 用户在我的系统中停止输入至少 100 毫秒后的方法 input q field 我试图通过使用这个逻辑来实现这一点answer https stackoverflow com a
  • 检测“文件下载”弹出窗口何时关闭

    我有一个网页 用 JSF 制作 其中一些链接允许用户获取 PDF 文件 当用户点击这样的链接时 会显示一个等待弹出窗口 它是一个模式面板 因为 PDF 的生成可能很长 并且一旦创建文件 IE 就会显示 文件下载 弹出窗口 建议 打开 保存
  • 从 GetLastError() 函数返回的错误代码中获取文本

    我需要获取从 GetLastError 函数获得的错误代码的文本 我看到了一些示例 但我想要一个获取代码并返回字符串的函数 谢谢大家 我猜你想要这样的东西 DWORD dwLastError GetLastError TCHAR lpBuf
  • RxJava - 链接请求和更新 UI

    我遇到的问题是这样的 我需要向服务器执行几个请求 下一个请求取决于前一个请求的结果 它们看起来像这样 缩写 Observable
  • 如何调试(最好在 IDE 中)MSBuild 脚本?

    我们非常广泛地使用 MSBuild 作为我们持续集成过程的一部分 虽然它非常强大 我们几乎可以在其中完成所有构建 测试和部署 利用一些自定义任务 我们发现使用标签对其进行调试是一种痛苦 并且不能总是为我们提供足够的信息 我发现 http w
  • 调用事件,h(args) 与 EventName?.Invoke()

    我总是这样调用事件 void onSomeEvent string someArg var h this EventName if h null h this new MyEventArgs someArg 今天 VS 2015 告诉我这可
  • 为什么 getSession() 在短时间内间隔的后续请求中不返回相同的会话?

    我正在发送一个 getJSON HTTP GET 请求两次 使用不同的数据 一次又一次 假设我们有 request1 和 request2 我可以在 FF 和 Chrome 的开发者工具中看到我有相同的cookie JSESSIONID F
  • 使用 leaflet.js 在点周围添加设定大小的正方形多边形

    有点奇怪 希望有人能帮忙 在传单中 一旦用户输入了纬度 经度并向地图添加了一个点 我希望能够在该点周围添加一个 10 公里的正方形 我尝试四处寻找计算方法来找到 x 公里外的正方形角点 但没有挖出任何东西 但肯定有更简单的方法 有人有想法吗
  • 如何在 Django 中创建多选框?

    我正在尝试创建多选框字段来自姜戈选择 2 https github com applegrew django select2库如下图所示 我使用了下一个代码 但它返回简单的选择多个小部件 我想我忘了补充一些东西 我的错误在哪里 有人可以告诉
  • 使用 stringstreams 将字符串转换为 __uint128_t

    我正在尝试从字符串中提取不同类型的数据 void readHeader char buf BUFFSIZE std istringstream hdr buf uint128 t id client hdr gt gt id client
  • C++:初始化结构体并设置函数指针

    我正在尝试使用函数指针初始化结构 但是除非使用全局函数完成 否则我很难这样做 以下代码有效 float tester float v return 2 0f v struct MyClass Example typedef float My
  • 为什么 Visual Studio 2019 不会运行我的单元测试?

    我在 VS2019 中看到 NUnit 测试的一些非常奇怪的行为 而相同的解决方案在 VS2017 中运行良好 我的脑海里有几个 NUnit 测试项目 在安装了 NUnit Runner 扩展的 VS2017 中 我可以在 测试资源管理器
  • 使用 java 执行 Matlab 函数

    我正在编写一个应用程序 它使用 matlab 进行图像处理 然后使用 Java 接口显示结果 由于某些原因 我必须同时使用 Java 和 Matlab 如何在java中使用matlab函数 如何创建和访问界面 MATLAB控制 http m
  • 有没有办法通过 Outlook API 获取建议的联系人?

    我目前正在开发一个应用程序来获取我的 Microsoft 帐户中的联系人 问题是 与 Google 不同 当我向新联系人发送电子邮件或从新联系人接收电子邮件时 该电子邮件不会复制到 我的联系人 中 因此我无法通过该电子邮件https out
  • 如何修复 Visual Studio Code 终端中的“分段错误”错误?

    在 Windows 10 上 我安装了 Visual Studio Code 当我打开终端 Git Bash 并输入less watch compiler 我收到错误 分段故障 但是如果我转到 Git Bash 终端本身 在 Visual
  • 重新创建 Siri 按钮发光动画

    有没有办法复制 Siri 按钮发光动画 它看起来绝对华丽 但我现在不知道如何开始 是否有在线预格式化的旋转PNG 或者是用CoreAnimation完成的 我相信 Siri 动画是用 CAEmitterLayer 和 CAEmitterCe
  • 渲染脚本渲染在Android上比OpenGL渲染慢很多

    背景 我想根据Android相机应用程序的代码添加实时滤镜 但Android相机应用程序的架构是基于OpenGL ES 1 x 我需要使用着色器来自定义我们的过滤器实现 然而 将相机应用程序更新到OpenGL ES 2 0太困难了 然后我必
  • 查询不可更新

    我正在尝试使用 BE SQL Server 2012 Express 中的记录更新本地 Access 2007 表 我的步骤在这里 SQL Server中存在带有4个参数的存储过程来获取所需的记录 Access VBA中有调用SP并进行临时
  • BitBucket+Jenkins:仅在特定分支更改时触发构建

    以下是该问题的据称解决方案 尽管它看起来确实是一种解决方法 而不是最终的解决方案 有没有一种方法 通过作业配置或 bitbucket 挂钩配置 我可以将作业设置为仅在推送到特定分支时运行构建 是否可以仅从一个特定分支触发 Jenkins h
  • PySide2/QML 填充 Gridview 模型/委托并为其设置动画

    我是 QML 的新手 正在寻求以下几点帮助 如何基于 TextField 输入 如 Regex 通过 PySide2 过滤 Gridview 模型中的 QAbstractListModel 数据 标题 如何在鼠标悬停时为 Gridview