2014-02-10 55 views
0

我需要在python中实现一个函数,它在按下“ctrl + v”时处理“粘贴”。我有一个QTableView,我需要复制表的一个字段并将其粘贴到表的另一个字段。我已经尝试了下面的代码,但问题是我不知道如何在tableView中读取复制的项目(来自剪贴板)。 (因为它已经复制了字段,我可以将它粘贴到其他任何地方,比如记事本)。这是我所试过的部分代码:粘贴在QTableView的字段

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) 

回答

2

您可以获取剪贴板形成用QApplication.clipboard()您的应用程序的QApplication实例,从QClipboard对象返回,你可以得到文字,aimge,MIME数据,等这里有一个例子:

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_() 

注:我已经使用了QTableWidget因为我没有一个模型QTableView使用,但您可以调整例如您的需求。

+0

AttributeError:'QTableView'对象没有属性'setItem' –

+1

你读过最后的笔记吗?我用'QTableWidget'而不是'QTableView'也检查代码;) –

+0

为什么这不是公认的答案? – pbreach