I'm trying to save an image to the system clipboard, so I wrote some code like this:
#!/usr/bin/python3
from PyQt5.Qt import QApplication
from PyQt5.QtWidgets import QWidget, QPushButton
from PyQt5.Qt import QImage
import sys
class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.button = QPushButton(self)
self.button.clicked.connect(self.copyPicToClip)
def copyPicToClip(self):
image = QImage('./test.jpg')
QApplication.clipboard().setImage(image)
self.close()
if __name__ == '__main__':
a = QApplication(sys.argv)
myW = MyWidget()
myW.show()
a.exec()
Sadly, I found it doesn't work at all. Then I tried to find a solution. The first thing I tried was this:
def copyPicToClip(self):
image = QImage('./test.jpg')
QApplication.clipboard().setImage(image)
# self.close()
After this, I just found that it worked, but the window does not close automatically.
Then I tried with copying text:
#!/usr/bin/python3
from PyQt5.Qt import QApplication, QClipboard
from PyQt5.QtWidgets import QWidget, QPushButton
from PyQt5.Qt import QImage
import sys
class MyWidget(QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.button = QPushButton(self)
self.button.clicked.connect(self.copyPicToClip)
QApplication.clipboard().dataChanged.connect(self.testFunc)
def copyPicToClip(self):
image = QImage('./test.jpg')
QApplication.clipboard().setImage(image)
def testFunc(self):
print('Here')
self.close()
if __name__ == '__main__':
a = QApplication(sys.argv)
myW = MyWidget()
myW.show()
a.exec()
Sadly, it failed again.
So, it seems that if I close the application to early, the image won't be saved to the clipboard. But I want to close it after copying the image to the clipboard.
Any suggestions?
(PyQt5, ubuntu 16.10, if helps).
Unfortunately for you, this is "normal" behaviour on Linux. By default, clipboard data is not persisted when an application closes. The usual work-around for this problem is to install a clipboard manager. For Ubuntu, see this wiki article for more details:
- Ubuntu Wiki: Clipboard Persistence
(NB: I have not actually tested any of the suggested solutions myself, so I don't know whether any of them will work with PyQt).
The basic problem is that on Linux, the clipboard only stores a reference to the underlying data. This is very efficient in terms of storage, because the data is only copied when the client program actually requests it. But of course if the source application closes, the reference will be invalidated, and the clipboard will become empty.
来源:https://stackoverflow.com/questions/40944657/image-copied-to-clipboard-doesnt-persist-on-linux