After printing the data on PYTHON QTableWidget, I want to copy and paste the multi-item elsewhere using the ctrl+c function.

Asked 2 years ago, Updated 2 years ago, 132 views

A lot of things were reflected in the title

The query results were output to QTableWidget.

Drag a certain part of the result with your mouse, select Ctrl+C, and

If you ctrl +v on the notebook pad or excel sheet, it's not as many items as you want.

Only one item is copied.

I'm posting a question because it doesn't solve well even if I look at stackoverflow.

Please tell me how to do it~

python3 pyqt

2022-09-22 20:00

1 Answers

The widget doesn't offer that function.

It should be implemented by registering keypress event on the table widget and copying the item and putting it on the clipboard when Ctrl+c.

Here's an example of what we tested.

import sys
import io
import csv
from PyQt5.Qt import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

data = {'col1':['1','2','3'], 'col2':['4','5','6'], 'col3':['7','8','9']}

class MyTable(QTableWidget):
    def __init__(self, data, *args):
        QTableWidget.__init__(self, *args)
        self.data = data
        self.setmydata()
        self.resizeColumnsToContents()
        self.resizeRowsToContents()
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

    def setmydata(self):

        horHeaders = []
        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)
            for m, item in enumerate(self.data[key]):
                newitem = QTableWidgetItem(item)
                self.setItem(m, n, newitem)
        self.setHorizontalHeaderLabels(horHeaders)

    def keyPressEvent(self, ev):
        if (ev.key() == Qt.Key_C) and (ev.modifiers() & Qt.ControlModifier): 
            self.copySelection()

    def copySelection(self):
        selection = self.selectedIndexes()
        if selection:
            rows = sorted(index.row() for index in selection)
            columns = sorted(index.column() for index in selection)
            rowcount = rows[-1] - rows[0] + 1
            colcount = columns[-1] - columns[0] + 1
            table = [[''] * colcount for _ in range(rowcount)]
            for index in selection:
                row = index.row() - rows[0]
                column = index.column() - columns[0]
                table[row][column] = index.data()
            stream = io.StringIO()
            csv.writer(stream).writerows(table)
            QApplication.clipboard().setText(stream.getvalue())


def main(args):
    app = QApplication(args)
    table = MyTable(data, 5, 3)
    table.show()
    sys.exit(app.exec_())

if __name__=="__main__":
    main(sys.argv)


2022-09-22 20:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.