Skip to content Skip to sidebar Skip to footer

Copy/paste Text From Qclipboard Freezes Program

I have a QTableWidget that when a row is clicked, it selects all cells in that row. I am trying to add a 'copy' functionality so that I can ^ctrl-c when row(s) are selected and pas

Solution 1:

You shouldn't use the dataChanged signal in this way for two reasons:

  • it will be called everytime the clipboard changes in the whole system;
  • clearing the clipboard will obviously change its content, resulting in a recursive call to your read_clipboard method; you could obviously temporarily disconnect the signal as suggested by @furas, but the first problem will remain.

Also, you can't use a QItemSelectionModel for setText, as it expects a string.

A better solution is to override the keyPressEvent of a custom QTableWidget class, to catch it's "copy" action before the default implementation acts upon it:

classMyTableWidget(QtWidgets.QTableWidget):
    defkeyPressEvent(self, event):
        if event == QtGui.QKeySequence.Copy:
            # set clipboard only if it's not a key repetitionifnot event.isAutoRepeat():
                QtWidgets.QApplication.clipboard().setText(', '.join(i.data() for i in self.selectedIndexes() if i.data()))
        else:
            super(MyTableWidget, self).keyPressEvent(event)

Another similar possibility is to install an event filter to your table and check for its key events:

classMyWindow(QtWidgets.QMainWindow):
    def__init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.my_tableWidget.installEventFilter(self)

    defeventFilter(self, source, event):
        if source == self.table and event.type() == QtCore.QEvent.KeyPress and event == QtGui.QKeySequence.Copy:
            ifnot 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)returnTruereturnsuper(MainWindow, self).eventFilter(source, event)

Post a Comment for "Copy/paste Text From Qclipboard Freezes Program"