PyQt clipboard doesn't copy to system clipboard

房东的猫 提交于 2020-01-29 11:53:10

问题


The following snippet of code doesn't seem to affect the system clipboard at all:

clipboard = QtGui.QApplication.clipboard()
clipboard.setText(text)

According to the Qt documentation, this is how you copy text to clipboard,

Why isn't it working?

Googling turned this up.

It suggests adding this after the above code:

event = QtCore.QEvent(QtCore.QEvent.Clipboard)
app.sendEvent(clipboard, event)

But this one behaves odd: it only copies the text to the clipboard after the program exits. Plus, some people in that link reported that this doesn't work with linux.

UPDATE:

Nevermind, I was doing something wrong else where, instead of binding the copy slot to the copy button, I connected it to the "quit" button.


回答1:


You may need to specify the mode.

This code worked for me on windows:

    cb = QtGui.QApplication.clipboard()
    cb.clear(mode=cb.Clipboard )
    cb.setText("Clipboard Text", mode=cb.Clipboard)



回答2:


I know you are not using Windows, but maybe this will give you some ideas... I used this in a PyQt program to copy URLs to the clipboard:

import win32clipboard

s = 'copy this to the clipboard'
try:
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardText(s)
    win32clipboard.CloseClipboard()
except:
    print 'Could not copy clipboard data.'



回答3:


You might try gtk.Clipboard from PyGTK. I believe it is multi-platform.

This might be part of the reason you're having trouble with PyQt's QClipboard object:

QClipboard QApplication.clipboard ()

Returns a pointer to the application global clipboard.

Note: The QApplication object should already be constructed before accessing the clipboard.

It's pointing to the application clipboard, not the system clipboard. You'll probably have to use something other than the QClipboard object to achieve your end.

Edit:

The above conclusion from the cited documentation is incorrect. According to the actual PyQt documentation of the QClipboard object:

The QClipboard class provides access to the window system clipboard.



来源:https://stackoverflow.com/questions/1073550/pyqt-clipboard-doesnt-copy-to-system-clipboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!