Reputation: 293
I need to implement a function in python which handles the "paste" when "ctrl+v" is pressed. I have a QTableView
, i need to copy a field of the table and paste it to another field of the table. I have tried the following code, but the problem is that i don't know how to read the copied item (from the clipboard) in the tableView. (As it already copies the field and i can paste it anywhere else like a notepad). Here is part of the code which I have tried:
class Widget(QWidget):
def __init__(self,md,parent=None):
QWidget.__init__(self,parent)
# initially construct the visible table
self.tv=QTableView()
self.tv.show()
# set the shortcut ctrl+v for paste
QShortcut(QKeySequence('Ctrl+v'),self).activated.connect(self._handlePaste)
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.tv)
# paste the value
def _handlePaste(self):
if self.tv.copiedItem.isEmpty():
return
stream = QDataStream(self.tv.copiedItem, QIODevice.ReadOnly)
self.tv.readItemFromStream(stream, self.pasteOffset)
Upvotes: 2
Views: 3331
Reputation: 17455
You can obtain the clipboard form the QApplication
instance of your app using QApplication.clipboard()
, and from the QClipboard
object returned you can get the text, image, mime data, etc. Here is an example:
import PyQt4.QtGui as gui
class Widget(gui.QWidget):
def __init__(self,parent=None):
gui.QWidget.__init__(self,parent)
# initially construct the visible table
self.tv=gui.QTableWidget()
self.tv.setRowCount(1)
self.tv.setColumnCount(1)
self.tv.show()
# set the shortcut ctrl+v for paste
gui.QShortcut(gui.QKeySequence('Ctrl+v'),self).activated.connect(self._handlePaste)
self.layout = gui.QVBoxLayout(self)
self.layout.addWidget(self.tv)
# paste the value
def _handlePaste(self):
clipboard_text = gui.QApplication.instance().clipboard().text()
item = gui.QTableWidgetItem()
item.setText(clipboard_text)
self.tv.setItem(0, 0, item)
print clipboard_text
app = gui.QApplication([])
w = Widget()
w.show()
app.exec_()
Note: I've used a QTableWidget
cause I don't have a model to use with QTableView
but you can adapt the example to your needs.
Upvotes: 6