Skip to main content
 首页 » 编程设计

python之如何使用 PySide2 实现响应式画廊 View

2024年11月01日11lovecherry

我正在为我们公司开发 Assets 管理应用程序。它是一个独立的 Python3 应用程序,使用 PySide2 并与我们的数据库后端对话。我正在编写的其中一个 View 应该是一个 HTML5 风格的响应式图库: Assets 显示为缩略图,鼠标悬停时它们会显示额外信息,单击它们会启动一个操作(例如在适当的应用程序中打开 Assets ).

在 PySide2/PyQt5 中实现它的最佳方法是什么?

因为我觉得在 HTML5 中实现和设计这样的东西很舒服,所以我倾向于使用 QWebEngineView 并在 python 中动态生成 HTML 和 CSS,然后使用 QWebEngineView.setHtml()显示它。

这是在不使用 HTML 的 PySide2 应用程序中执行此操作的好方法吗?是否有更多类似 Qt 的方法来实现动态、响应式、可样式化的画廊?

如果我使用 QWebEngineView,我将如何拦截用户点击其中一个 HTML 元素?我发现了这个问题,这听起来像是一个解决方案:Capture server response with QWebEngineView .有更简单的解决方案吗?

请您参考如下方法:

Qt 为您提供了许多替代方案(它们不是完整的解决方案,因为您没有明确指出您需要什么):


mouse-over效果的实现就不实现了,因为我不是前端专家,我会专注于双方的沟通。


要将 Python 信息传递给 JS,您可以使用 QWebEnginePage 的 runJavaScript() 方法和/或使用 QWebChannel,以及使用 QWebChannel 的相反部分(我不排除 QWebEngineUrlRequestInterceptor 可能是替代解决方案的想法但在这种情况下,以前的解决方案更简单)。所以在这种情况下,我将使用 QWebChannel。

想法是注册一个通过信号(在本例中为 JSON)发送信息的 QObject,在 javascript 解析 JSON 和创建动态 HTML 的同时,然后在诸如点击之类的任何事件之前调用 QObject 的插槽.

综合以上,解决方案是:

├── index.html 
├── index.js 
└── main.py 
import json 
from PySide2 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets, QtWebChannel 
 
 
class GalleryManager(QtCore.QObject): 
    dataChanged = QtCore.Signal(str) 
 
    def __init__(self, parent=None): 
        super().__init__(parent) 
        self._data = [] 
        self._is_loaded = False 
 
    @QtCore.Slot(str) 
    def make_action(self, identifier): 
        print(identifier) 
 
    @QtCore.Slot() 
    def initialize(self): 
        self._is_loaded = True 
        self.send_data() 
 
    def send_data(self): 
        if self._is_loaded: 
            self.dataChanged.emit(json.dumps(self._data)) 
 
    @property 
    def data(self): 
        return self._data 
 
    @data.setter 
    def data(self, d): 
        self._data = d 
        self.send_data() 
 
 
if __name__ == "__main__": 
    import os 
    import sys 
 
    # sys.argv.append("--remote-debugging-port=8000") 
 
    app = QtWidgets.QApplication(sys.argv) 
 
    current_dir = os.path.dirname(os.path.realpath(__file__)) 
 
    view = QtWebEngineWidgets.QWebEngineView() 
    channel = QtWebChannel.QWebChannel(view) 
    gallery_manager = GalleryManager(view) 
    channel.registerObject("gallery_manager", gallery_manager) 
    view.page().setWebChannel(channel) 
 
    def on_load_finished(ok): 
        if not ok: 
            return 
        data = [] 
        for i, path in enumerate( 
            ( 
                "https://source.unsplash.com/pWkk7iiCoDM/400x300", 
                "https://source.unsplash.com/aob0ukAYfuI/400x300", 
                "https://source.unsplash.com/EUfxH-pze7s/400x300", 
                "https://source.unsplash.com/M185_qYH8vg/400x300", 
                "https://source.unsplash.com/sesveuG_rNo/400x300", 
                "https://source.unsplash.com/AvhMzHwiE_0/400x300", 
                "https://source.unsplash.com/2gYsZUmockw/400x300", 
                "https://source.unsplash.com/EMSDtjVHdQ8/400x300", 
                "https://source.unsplash.com/8mUEy0ABdNE/400x300", 
                "https://source.unsplash.com/G9Rfc1qccH4/400x300", 
                "https://source.unsplash.com/aJeH0KcFkuc/400x300", 
                "https://source.unsplash.com/p2TQ-3Bh3Oo/400x300", 
            ) 
        ): 
            d = {"url": path, "identifier": "id-{}".format(i)} 
            data.append(d) 
        gallery_manager.data = data 
 
    view.loadFinished.connect(on_load_finished) 
 
    filename = os.path.join(current_dir, "index.html") 
    view.load(QtCore.QUrl.fromLocalFile(filename)) 
    view.resize(640, 480) 
    view.show() 
 
    sys.exit(app.exec_()) 
<!DOCTYPE html> 
<html> 
 
<head> 
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> 
 
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> 
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> 
 
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script> 
 
    <script type="text/javascript" src="index.js"> </script> 
 
</head> 
 
<body> 
    <div class="container"> 
        <h1 class="font-weight-light text-center text-lg-left mt-4 mb-0">Thumbnail Gallery</h1> 
        <hr class="mt-2 mb-5"> 
        <div id="container" class="row text-center text-lg-left"> 
        </div> 
    </div> 
</body> 
</html> 
var gallery_manager = null; 
 
new QWebChannel(qt.webChannelTransport, function (channel) { 
    gallery_manager = channel.objects.gallery_manager; 
 
    gallery_manager.dataChanged.connect(populate_gallery); 
    gallery_manager.initialize(); 
}); 
 
 
function populate_gallery(data) { 
    const container = document.getElementById('container'); 
    // clear 
    while (container.firstChild) { 
        container.removeChild(container.firstChild); 
    } 
    // parse json 
    var d = JSON.parse(data); 
    // fill data 
    for (const e of d) { 
        var identifier = e["identifier"]; 
        var url = e["url"]; 
        var div_element = create_div(identifier, url)  
        container.appendChild(div_element); 
    } 
 
} 
 
function create_div(identifier, url){ 
    var html = ` 
        <div class="d-block mb-4 h-100"> 
            <img class="img-fluid img-thumbnail" src="${url}" alt=""> 
        </div> 
        ` 
    var div_element = document.createElement("div"); 
    div_element.className = "col-lg-3 col-md-4 col-6" 
    div_element.innerHTML = html; 
    div_element.addEventListener('click', function (event) { 
        gallery_manager.make_action(identifier); 
    }); 
    return div_element; 
}