如何在 PyQt 应用程序退出时禁用剪贴板清除? [英] How can I disable clear of clipboard on exit of PyQt application?

查看:24
本文介绍了如何在 PyQt 应用程序退出时禁用剪贴板清除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 PyQt4 应用程序(参见下面的代码),它揭示了一个问题:如果我从 QLineEdit 中选择文本并将其复制到剪贴板,然后我可以将其粘贴到另一个应用程序只有在我的应用程序运行时.似乎在退出时,PyQt 应用程序会清除剪贴板,因此在应用程序关闭后我无法粘贴文本.

我该怎么做才能避免这个问题?

PyQt 4.4.3 @ Python 2.5 @ Windows XP.在 PyQt 4.5+ 和 Linux 上也证实了这种效果.

导入系统从 PyQt4 导入 QtGuiapp = QtGui.QApplication(sys.argv)编辑 = QtGui.QLineEdit()edit.setText('foo bar')编辑显示()app.exec_()

解决方案

OK,有没有完全清除剪贴板的情况发生.只是 QT 在剪贴板中存储某种文本指针,而不仅仅是文本.Gordon Tyler 向我指出了 PyQt 邮件列表上的这个讨论解释发生了什么.我引用了代码和相关部分的解释.

在应用程序退出时运行此代码(例如在 closeEvent 处理程序中):

 from PyQt4 import QtGui, QtCore剪贴板 = QtGui.QApplication.clipboard()事件 = QtCore.QEvent(QtCore.QEvent.Clipboard)QtGui.QApplication.sendEvent(剪贴板,事件)

<块引用>

这背后的基本概念是默认复制一些东西到剪贴板只复制一个引用/指针到源应用.然后当另一个应用程序想要粘贴数据时它从剪贴板请求来自源应用程序的数据.调用 OleFlushClipboard 会导致 Windows 复制真实数据到剪贴板而不是参考.虽然这确实会导致复制图像时的延迟,它应该没有任何明显的影响带字符串.

上面的代码是非常跨平台的,不会对 Linux 平台产生任何不良影响.

I have a simple PyQt4 application (see the code below) that reveals a problem: if I select the text from a QLineEdit and copy it to the clipboard, then I can paste it to another application only while my application is running. It seems that on exit, PyQt application clears the clipboard so I can't paste the text after the application is closed.

What can I do to avoid this problem?

PyQt 4.4.3 @ Python 2.5 @ Windows XP. Also this effect confirmed on PyQt 4.5+, and on Linux too.

import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
edit = QtGui.QLineEdit()
edit.setText('foo bar')
edit.show()
app.exec_()

解决方案

OK, there is not exactly clear of clipboard occurs. Just QT store some sort of pointer of text in the clipboard instead of just text. Gordon Tyler has pointed me to this discussion on the PyQt mailing list which explains what's going on. I quote code and relevant part of explanation.

Run this code on exit of application (e.g. in closeEvent handler):

   from PyQt4 import QtGui, QtCore
   clipboard = QtGui.QApplication.clipboard()
   event = QtCore.QEvent(QtCore.QEvent.Clipboard)
   QtGui.QApplication.sendEvent(clipboard, event)

The basic concept behind this is that by default copying something into the clipboard only copies a reference/pointer to the source application. Then when another application wants to paste the data from the clipboard it requests the data from the source application. Calling OleFlushClipboard causes Windows to copy the real data into the clipboard instead of the reference. While this does cause a delay when copying images, it should not have any noticeable impact with strings.

The code above is pretty cross-platform and don't make any bad impact on Linux platform.

这篇关于如何在 PyQt 应用程序退出时禁用剪贴板清除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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