Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

python - Paste in the field of QTableView

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...