首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从QClipboard冻结程序复制/粘贴文本

从QClipboard冻结程序复制/粘贴文本
EN

Stack Overflow用户
提问于 2019-07-29 19:07:40
回答 1查看 691关注 0票数 1

我有一个QTableWidget,当单击一行时,它会选择该行中的所有单元格。我正在尝试添加一个“复制”功能,以便在选中行并粘贴到文本编辑器中时,我能够^ctrl。但是,在我的当前代码中,一旦我^ctrl一行被复制,我复制的行就会继续被复制。

我在我的方法"read_clipboard“中实现了一个print语句,以查看复制的行是否被读取,这就是我如何发现该行一直被复制,就像在一个无限循环中一样。

以前关于PyQt/Qt和QClipboard的堆栈溢出问题对我都没有任何效果。

代码语言:javascript
复制
def __init__(self):
   super(MainWindow, self).__init__()
   self.setupUi(self)
   self.my_selector = self.my_tableWidget.selectionModel()

   # Where I detect the signal to call my "read_clipboard" method
   QtGui.QGuiApplication.clipboard().dataChanged.connect(self.read_clipboard)

   self.show()

def read_clipboard(self):
    selection = self.my_selector.selectedIndexes()
    if selection:
        print(selection)
        QtGui.QGuiApplication.clipboard().clear()
        QtGui.QGuiApplication.clipboard().setText(selection)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()  # Creates MainWindow object
    ret = app.exec_()
    sys.exit(ret)

当我^ctrl一行时,程序就像在一个无限循环中一样连续地打印“选择”,我不知道如何在它只运行一次之后停止它,这样我就可以复制这一行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-29 22:31:23

您不应该以这种方式使用dataChanged信号,原因有二:

  • 每次剪贴板在系统中发生变化时,都会调用剪贴板;
  • 清除剪贴板显然会改变其内容,导致对read_clipboard方法的递归调用;您显然可以按照@furas的建议暂时断开信号,但第一个问题仍然存在。

而且,您不能使用QItemSelectionModel作为setText,因为它需要一个字符串。

更好的解决方案是重写自定义QTableWidget类的QTableWidget,在默认实现对其生效之前捕获它的“复制”操作:

代码语言:javascript
复制
class MyTableWidget(QtWidgets.QTableWidget):
    def keyPressEvent(self, event):
        if event == QtGui.QKeySequence.Copy:
            # set clipboard only if it's not a key repetition
            if not event.isAutoRepeat():
                QtWidgets.QApplication.clipboard().setText(', '.join(i.data() for i in self.selectedIndexes() if i.data()))
        else:
            super(MyTableWidget, self).keyPressEvent(event)

另一种类似的可能性是在表中安装事件筛选器并检查其关键事件:

代码语言:javascript
复制
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.my_tableWidget.installEventFilter(self)

    def eventFilter(self, source, event):
        if source == self.table and event.type() == QtCore.QEvent.KeyPress and event == QtGui.QKeySequence.Copy:
            if not event.isAutoRepeat():
                QtWidgets.QApplication.clipboard().setText(', '.join(i.data() for i in self.table.selectedIndexes() if i.data()))
            # return True to ensure that the event is not actually propagated
            # to the table widget, nor its parent(s)
            return True
        return super(MainWindow, self).eventFilter(source, event)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57260037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档