我有一个QTableWidget,当单击一行时,它会选择该行中的所有单元格。我正在尝试添加一个“复制”功能,以便在选中行并粘贴到文本编辑器中时,我能够^ctrl。但是,在我的当前代码中,一旦我^ctrl一行被复制,我复制的行就会继续被复制。
我在我的方法"read_clipboard“中实现了一个print语句,以查看复制的行是否被读取,这就是我如何发现该行一直被复制,就像在一个无限循环中一样。
以前关于PyQt/Qt和QClipboard的堆栈溢出问题对我都没有任何效果。
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一行时,程序就像在一个无限循环中一样连续地打印“选择”,我不知道如何在它只运行一次之后停止它,这样我就可以复制这一行。
发布于 2019-07-29 22:31:23
您不应该以这种方式使用dataChanged信号,原因有二:
read_clipboard方法的递归调用;您显然可以按照@furas的建议暂时断开信号,但第一个问题仍然存在。而且,您不能使用QItemSelectionModel作为setText,因为它需要一个字符串。
更好的解决方案是重写自定义QTableWidget类的QTableWidget,在默认实现对其生效之前捕获它的“复制”操作:
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)另一种类似的可能性是在表中安装事件筛选器并检查其关键事件:
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)https://stackoverflow.com/questions/57260037
复制相似问题