粘贴在QTableView的字段中 [英] Paste in the field of QTableView

查看:102
本文介绍了粘贴在QTableView的字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

您可以使用 QApplication.clipboard() 从应用的 QApplication 实例中获取剪贴板,从返回的 QClipboard 对象中,您可以获得文本、图像、mime 数据等.这是一个示例:

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

注意:我使用了 QTableWidget 因为我没有与 QTableView 一起使用的模型,但您可以根据需要调整示例.

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.

这篇关于粘贴在QTableView的字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆