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

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

问题描述

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

 <代码>#!/usr/bin/python导入系统从PyQt5.QtWidgets导入QApplication,QWidgetdef main():应用= 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())#是print(mime.imageData())#无sys.exit(app.exec_())如果__name__ =='__main__':主要的() 

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

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

解决方案

hasImage()返回True并不意味着 imageData()返回QImage,因为它仅表示用户已将图像复制到剪贴板,我应以哪种格式复制图像?好吧,它可以是png,jpg等,也可以提供供客户端应用程序下载的url或html,以将其插入客户端应用程序,然后通过渲染HTML获得图像.

因此,通常,从中复制图像的应用程序负责发送格式,并且该格式没有严格的标准,但是有常见的格式.

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

 <代码>#!/usr/bin/python导入系统从functools导入cached_property从PyQt5.QtCore导入pyqtSignal,QObject,QUrl从PyQt5.QtNetwork导入QNetworkAccessManager,QNetworkRequest,QNetworkReply从PyQt5.QtGui导入QGuiApplication,QImage,QPixmap从PyQt5.QtWidgets导入QApplication,QWidget,QLabel从bs4导入BeautifulSoup类ImageDownloader(QObject):完成= pyqtSignal(QImage)def __init __(self,parent = None):super().__ init __(父母)self.manager.finished.connect(self.handle_finished)@cached_propertydef经理(个体):返回QNetworkAccessManager()def start_download(self,url):self.manager.get(QNetworkRequest(url))def handle_finished(自己,回复):如果reply.error()!= QNetworkReply.NoError:打印(错误:",reply.errorString())返回图片= QImage()image.loadFromData(reply.readAll())self.finished.emit(图片)ClipboardManager(QObject)类:imageChanged = pyqtSignal(QImage)def __init __(self,parent = None):super().__ init __(父母)QGuiApplication.clipboard().dataChanged.connect(self.handle_clipboard_datachanged)self.downloader.finished.connect(self.imageChanged)@cached_propertydef下载器(自己):返回ImageDownloader()def handle_clipboard_datachanged(自己):mime = QGuiApplication.clipboard().mimeData()如果mime.hasImage():图片= mime.imageData()如果图像不是无:self.imageChanged.emit(image)elif mime.hasUrls():url = mime.urls()[0]self.downloader.start_download(URLs [0])elif mime.hasHtml():html = mime.html()汤= BeautifulSoup(html,features ="lxml")imgs = soup.findAll("img")如果imgs:url = QUrl.fromUserInput(imgs [0] ["src"])self.downloader.start_download(网址)别的:对于mime.formats()中的fmt:打印(fmt,mime.data(fmt))def main():应用= QApplication(sys.argv)标签= QLabel(scaledContents = True)label.resize(250,150)label.move(300,300)label.setWindowTitle(简单")label.show()经理= ClipboardManager()manager.imageChanged.connect(lambda图片:label.setPixmap(QPixmap.fromImage(image)))sys.exit(app.exec_())如果__name__ =="__main__":主要的() 

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()

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?

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

解决方案

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.

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()

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

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