`mime.hasImage()` 返回 `true` 但 `mime.imageData()` 在 Linux 上返回 `None` [英] `mime.hasImage()` returns `true` but `mime.imageData()` returns `None` on Linux

查看:12
本文介绍了`mime.hasImage()` 返回 `true` 但 `mime.imageData()` 在 Linux 上返回 `None`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Linux上运行一个简单的PyQt5应用程序,代码如下:

I'm trying to run a simple PyQt5 application on Linux, the code is as follows:

#!/usr/bin/python

import sys
from PyQt5.QtWidgets import QApplication, QWidget


def main():
    app = QApplication(sys.argv)

    w = QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    w.show()

    mime = app.clipboard().mimeData()
    print(mime.hasImage())  # True
    print(mime.imageData())  # None

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

在运行它之前,我将图像复制到剪贴板,所以 mime.hasImage() 应该返回 True.没问题,也是这样.但奇怪的是,mime.imageData() 有时会返回 None.那不应该发生.mime.imageData() 应该包含我复制的图像,而不是 None.代码有什么问题吗?

Before running it, I copied an image into the clipboard, so mime.hasImage() should return True. No problem, that's also the case. But what's weird is, mime.imageData() sometimes returns None. that shouldn't happen. mime.imageData() should contain the image that I copied instead of None. Is there anything wrong with the code?

顺便说一句,这似乎只发生在 Linux 上,mime.imageData() 在 Windows 上永远不会返回 None.我正在使用python3

By the way, this seems to only happen on Linux, mime.imageData() never returns None on Windows. I'm using python3

推荐答案

hasImage() 返回 True 并不意味着 imageData() 返回 QImage,因为它只是表示用户将图像复制到剪贴板,我以什么格式复制图像?嗯,可以是png、jpg等,也可以是提供url供客户端下载,也可以提供html插入到客户端,然后通过渲染HTML获取图片.

That hasImage() returns True does not imply that imageData() returns a QImage since it only indicates that the user copied an image to the clipboard, and in what format do I copy the image? Well, it could be png, jpg, etc or it could provide the url for the client application to download or html to insert it into the client application and then obtain the image by rendering the HTML.

因此,一般来说,复制图像的应用程序负责发送格式,并且该格式没有限制性标准,但有通用格式.

So in general the application from which the image was copied is responsible for the sending format and that there is no restrictive standard for that format but there are common formats.

以下示例显示了处理来自 url 和 HTML 的图像的逻辑:

The following example shows the logic to handle the images that come from urls and HTML:

#!/usr/bin/python

import sys
from functools import cached_property

from PyQt5.QtCore import pyqtSignal, QObject, QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
from PyQt5.QtGui import QGuiApplication, QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QLabel

from bs4 import BeautifulSoup


class ImageDownloader(QObject):
    finished = pyqtSignal(QImage)

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

        self.manager.finished.connect(self.handle_finished)

    @cached_property
    def manager(self):
        return QNetworkAccessManager()

    def start_download(self, url):
        self.manager.get(QNetworkRequest(url))

    def handle_finished(self, reply):
        if reply.error() != QNetworkReply.NoError:
            print("error: ", reply.errorString())
            return
        image = QImage()
        image.loadFromData(reply.readAll())
        self.finished.emit(image)


class ClipboardManager(QObject):
    imageChanged = pyqtSignal(QImage)

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

        QGuiApplication.clipboard().dataChanged.connect(
            self.handle_clipboard_datachanged
        )

        self.downloader.finished.connect(self.imageChanged)

    @cached_property
    def downloader(self):
        return ImageDownloader()

    def handle_clipboard_datachanged(self):
        mime = QGuiApplication.clipboard().mimeData()
        if mime.hasImage():
            image = mime.imageData()
            if image is not None:
                self.imageChanged.emit(image)
            elif mime.hasUrls():
                url = mime.urls()[0]
                self.downloader.start_download(urls[0])
            elif mime.hasHtml():
                html = mime.html()
                soup = BeautifulSoup(html, features="lxml")
                imgs = soup.findAll("img")
                if imgs:
                    url = QUrl.fromUserInput(imgs[0]["src"])
                    self.downloader.start_download(url)
            else:
                for fmt in mime.formats():
                    print(fmt, mime.data(fmt))


def main():
    app = QApplication(sys.argv)

    label = QLabel(scaledContents=True)
    label.resize(250, 150)
    label.move(300, 300)
    label.setWindowTitle("Simple")
    label.show()

    manager = ClipboardManager()
    manager.imageChanged.connect(
        lambda image: label.setPixmap(QPixmap.fromImage(image))
    )

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

这篇关于`mime.hasImage()` 返回 `true` 但 `mime.imageData()` 在 Linux 上返回 `None`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆