PySide6 Copy and Past from clipboard to QTableWedget - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: PySide6 Copy and Past from clipboard to QTableWedget (/thread-41246.html) |
PySide6 Copy and Past from clipboard to QTableWedget - zinho - Dec-05-2023 Hi. I'm using PySide6 - 6.6.0 I have UI maide by QTDesigner with 3 tables one of them called tb_segregados When main.py run, will display GUI to user fill up this table. The user have this options: 1 fill the table and press printer button to send to the printer. 2 Copy from (Excel, CSV or Text file) paste on table and press printer button to send to the printer. I looked for something and try adapt, but it's not working. look at to my files (1. main.py, 2. ui_mainwindow.py), into googledrive. https://drive.google.com/drive/folders/1Gd6OPkPpNtkjTMwRZOwxG2XTvHHH3SfE?usp=drive_link Thanks RE: PySide6 Copy and Past from clipboard to QTableWedget - deanhystad - Dec-05-2023 Forget about designer and three tables and try to get this working with one table. This way you will have a small example program you can post with your questions. Posting code is the best way to provide all the details we need to know to help you with your issue. Is b_segregados a QTableView? See attached link that talks about two ways to print the table. One is to copy the table to a QTextDocument and print that. The other prints directly from the table. https://stackoverflow.com/questions/12099152/how-to-print-a-qtableview I tried using a designer tool before I was familiar with Qt. It did not work well for me. Designers hide implementation details that you really need to know about. After I learned how to make GUI programs manually, I was able to use the designer efficiently and not be dumbfounded when the program didn't work. I also realized that for most of the programs I write, using a designer slows me down. RE: PySide6 Copy and Past from clipboard to QTableWedget - zinho - Dec-05-2023 Hi To be more eazy, I'm posting my two files here. Tks RE: PySide6 Copy and Past from clipboard to QTableWedget - deanhystad - Dec-05-2023 Post code, not links to code. RE: PySide6 Copy and Past from clipboard to QTableWedget - zinho - Dec-05-2023 Hi. This is may main.py file import sys from PySide6 import QtWidgets from ui_mainwindow import Ui_Dialog from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QVBoxLayout, QLabel, QMessageBox, QApplication) from PySide6.QtCore import Qt #from test_zpl import run_printer2 class CustomDialog(QDialog): def __init__(self): super().__init__() self.setWindowTitle("Confirme sua impressão.") QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel self.buttonBox = QDialogButtonBox(QBtn) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.layout = QVBoxLayout() message = QLabel("Deseja executar a impressão?") self.layout.addWidget(message) self.layout.addWidget(self.buttonBox) self.setLayout(self.layout) class MainWindow(QtWidgets.QMainWindow, Ui_Dialog, CustomDialog): def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.main_tab.setCurrentIndex(4) self.cb_setores.addItems(["Devolução","Maturação de Gelo","Recebimento","Segregados","Informação"]) self.cb_setores.setCurrentIndex(4) self.cb_setores.currentIndexChanged.connect(self.index_changed) # Button to print data self.pb_print.clicked.connect(self.get_data_from_table) # set up table colunas_seg = ["Laboratório", "Código Fornecedor", "Material", "Lote", "Quantidade", "Descrição", "UD", "CD", "Volume"] self.tb_segregados.setHorizontalHeaderLabels(colunas_seg) def index_changed(self, index): self.main_tab.setCurrentIndex(index) def get_data_from_table(self, s): #run_printer2(opt=dic_segreg) # Passar um Dict como parametro. self.msg = CustomDialog() if self.msg.exec(): dlg = QMessageBox(self) dlg.setWindowTitle("Impressão!") dlg.setText("Dados enviado para impressora!") button = dlg.exec() if button == QMessageBox.Ok: print("Dados enviado para impressora!") else: print("Impressão cancelada!") def keyPressEvent(self, event) -> None: # Font: https://github.com/ingwant/PyQt5-Video-Book super().keyPressEvent(event) try: # Check keyboard input(Ctrl + V) to accomplish of paste if event.key() == Qt.Key.Key_V and (event.modifiers() & Qt.KeyboardModifier.ControlModifier): selection = self.tb_segregados.selectedIndexes() if selection: # Get the first selected cell position row_anchor = selection[0].row() column_anchor = selection[0].column() # Create clipboard object to read data from clipboard clipboard = QApplication.clipboard() # Get data list from clipboard rows = clipboard.text().split('\n') # Add more rows if current row count doesn't match the new row count needed if self.tb_segregados.rowCount() < row_anchor + len(rows) - 1: self.tb_segregados.setRowCount(row_anchor + len(rows) - 1) # Show data in table widget which gets from Excel file for index_row, row in enumerate(rows): values = row.split("\t") for index_col, value in enumerate(values): item = self.tb_segregados(value) self.tb_segregados.setItem(row_anchor + index_row, column_anchor + index_col, item) # Check keyboard input(Ctrl + C) to accomplish copy # Check keyboard input(Ctrl + X) to accomplish cut if (event.key() == Qt.Key.Key_C or event.key() == Qt.Key.Key_X) \ and (event.modifiers() & Qt.KeyboardModifier.ControlModifier): # get the selection section data copied_cell = sorted(self.tb_segregados.selectedIndexes()) # Define a variable to save selected data copy_text = "" max_column = copied_cell[-1].column() for cell in copied_cell: # Get each cell text cell_item = self.tb_segregados.item(cell.row(), cell.column()) if cell_item: copy_text += cell_item.text() # Clear data in table widget when it cuts data if event.key() == Qt.Key.Key_X: cell_item.setText("") else: copy_text += "" # Format the copied data for paste into Excel file if cell.column() == max_column: copy_text += "\n" else: copy_text += "\t" # Save data into clipboard QApplication.clipboard().setText(copy_text) except Exception as e: print(e) pass app = QtWidgets.QApplication(sys.argv) window = MainWindow() window.show() app.exec()This is may ui_mainwindow.py file # -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'mainwindowYgPvkx.ui' ## ## Created by: Qt User Interface Compiler version 6.6.0 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt) from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QGradient, QIcon, QImage, QKeySequence, QLinearGradient, QPainter, QPalette, QPixmap, QRadialGradient, QTransform) from PySide6.QtWidgets import (QApplication, QComboBox, QDialog, QFrame, QHeaderView, QLabel, QPushButton, QSizePolicy, QStackedWidget, QTableWidget, QTableWidgetItem, QWidget) class Ui_Dialog(object): def setupUi(self, Dialog): if not Dialog.objectName(): Dialog.setObjectName(u"Dialog") Dialog.resize(1042, 514) self.frame = QFrame(Dialog) self.frame.setObjectName(u"frame") self.frame.setGeometry(QRect(10, 20, 1021, 71)) self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.cb_setores = QComboBox(self.frame) self.cb_setores.setObjectName(u"cb_setores") self.cb_setores.setGeometry(QRect(10, 11, 401, 31)) font = QFont() font.setFamilies([u"Arial"]) font.setPointSize(12) font.setBold(True) self.cb_setores.setFont(font) self.cb_setores.setStyleSheet(u"background-color: rgb(85, 170, 255);") self.pb_print = QPushButton(self.frame) self.pb_print.setObjectName(u"pb_print") self.pb_print.setGeometry(QRect(864, 3, 101, 41)) font1 = QFont() font1.setFamilies([u"Arial"]) font1.setPointSize(10) font1.setBold(True) self.pb_print.setFont(font1) self.pb_print.setCursor(QCursor(Qt.PointingHandCursor)) self.frame_2 = QFrame(Dialog) self.frame_2.setObjectName(u"frame_2") self.frame_2.setGeometry(QRect(10, 100, 1021, 371)) self.frame_2.setStyleSheet(u"background-color: rgb(169, 170, 156);") self.frame_2.setFrameShape(QFrame.StyledPanel) self.frame_2.setFrameShadow(QFrame.Raised) self.main_tab = QStackedWidget(self.frame_2) self.main_tab.setObjectName(u"main_tab") self.main_tab.setGeometry(QRect(10, 10, 1001, 351)) self.main_tab.setStyleSheet(u"background-color: rgb(170, 170, 127);") self.pg_devolucao = QWidget() self.pg_devolucao.setObjectName(u"pg_devolucao") self.lb_devolucao = QLabel(self.pg_devolucao) self.lb_devolucao.setObjectName(u"lb_devolucao") self.lb_devolucao.setGeometry(QRect(20, 10, 121, 21)) font2 = QFont() font2.setFamilies([u"Arial"]) font2.setPointSize(14) font2.setBold(True) self.lb_devolucao.setFont(font2) self.tb_dev = QTableWidget(self.pg_devolucao) if (self.tb_dev.columnCount() < 9): self.tb_dev.setColumnCount(9) if (self.tb_dev.rowCount() < 4): self.tb_dev.setRowCount(4) self.tb_dev.setObjectName(u"tb_dev") self.tb_dev.setGeometry(QRect(10, 50, 971, 300)) self.tb_dev.setRowCount(4) self.tb_dev.setColumnCount(9) self.main_tab.addWidget(self.pg_devolucao) self.pg_mat_gelo = QWidget() self.pg_mat_gelo.setObjectName(u"pg_mat_gelo") self.lb_mat_gelo = QLabel(self.pg_mat_gelo) self.lb_mat_gelo.setObjectName(u"lb_mat_gelo") self.lb_mat_gelo.setGeometry(QRect(20, 10, 171, 21)) self.lb_mat_gelo.setFont(font2) self.main_tab.addWidget(self.pg_mat_gelo) self.pg_recebimento = QWidget() self.pg_recebimento.setObjectName(u"pg_recebimento") self.lb_recebimento = QLabel(self.pg_recebimento) self.lb_recebimento.setObjectName(u"lb_recebimento") self.lb_recebimento.setGeometry(QRect(20, 10, 121, 21)) self.lb_recebimento.setFont(font2) self.tb_recebimento = QTableWidget(self.pg_recebimento) if (self.tb_recebimento.columnCount() < 9): self.tb_recebimento.setColumnCount(9) if (self.tb_recebimento.rowCount() < 4): self.tb_recebimento.setRowCount(4) self.tb_recebimento.setObjectName(u"tb_recebimento") self.tb_recebimento.setGeometry(QRect(10, 50, 971, 300)) self.tb_recebimento.setRowCount(4) self.tb_recebimento.setColumnCount(9) self.main_tab.addWidget(self.pg_recebimento) self.pg_segregados = QWidget() self.pg_segregados.setObjectName(u"pg_segregados") self.lb_segregados = QLabel(self.pg_segregados) self.lb_segregados.setObjectName(u"lb_segregados") self.lb_segregados.setGeometry(QRect(20, 10, 121, 21)) self.lb_segregados.setFont(font2) self.tb_segregados = QTableWidget(self.pg_segregados) if (self.tb_segregados.columnCount() < 9): self.tb_segregados.setColumnCount(9) if (self.tb_segregados.rowCount() < 4): self.tb_segregados.setRowCount(4) self.tb_segregados.setObjectName(u"tb_segregados") self.tb_segregados.setGeometry(QRect(10, 50, 971, 300)) self.tb_segregados.setRowCount(4) self.tb_segregados.setColumnCount(9) self.main_tab.addWidget(self.pg_segregados) self.pd_default = QWidget() self.pd_default.setObjectName(u"pd_default") self.lb_default = QLabel(self.pd_default) self.lb_default.setObjectName(u"lb_default") self.lb_default.setGeometry(QRect(70, 20, 651, 101)) font3 = QFont() font3.setFamilies([u"Arial"]) font3.setPointSize(16) font3.setBold(True) self.lb_default.setFont(font3) self.lb_default.setWordWrap(True) self.main_tab.addWidget(self.pd_default) self.retranslateUi(Dialog) self.main_tab.setCurrentIndex(2) QMetaObject.connectSlotsByName(Dialog) # setupUi def retranslateUi(self, Dialog): Dialog.setWindowTitle(QCoreApplication.translate("Dialog", u"Dialog", None)) self.pb_print.setText(QCoreApplication.translate("Dialog", u"Imprimir", None)) self.lb_devolucao.setText(QCoreApplication.translate("Dialog", u"Devolu\u00e7\u00e3o", None)) self.lb_mat_gelo.setText(QCoreApplication.translate("Dialog", u"Matura\u00e7\u00e3o de Gelo", None)) self.lb_recebimento.setText(QCoreApplication.translate("Dialog", u"Recebimento", None)) self.lb_segregados.setText(QCoreApplication.translate("Dialog", u"Segregados", None)) self.lb_default.setText(QCoreApplication.translate("Dialog", u"Favor escolher um setor para iniciar o processo de impress\u00e3o. Use a caixa de combina\u00e7\u00e3o acima para selecionar a op\u00e7\u00e3o desejada.", None)) # retranslateUiTks RE: PySide6 Copy and Past from clipboard to QTableWedget - Axel_Erfurt - Dec-06-2023 I advise you to start from the beginning without using the designer. Use layouts instead of setGeometry(). RE: PySide6 Copy and Past from clipboard to QTableWedget - zinho - Dec-07-2023 I think this can help me, I will test it def keyPressEvent(self, event) -> None: super().keyPressEvent(event) try: if event.key() == Qt.Key.Key_V and (event.modifiers() & Qt.KeyboardModifier.ControlModifier): selection = self.tb_segregados.selectedIndexes() if selection: row_anchor = selection[0].row() column_anchor = selection[0].column() clipboard = QApplication.clipboard() rows = clipboard.text().split('\n') if self.tb_segregados.rowCount() < row_anchor + len(rows) - 1: self.tb_segregados.setRowCount(row_anchor + len(rows) - 1) for index_row, row in enumerate(rows): values = row.split("\t") for index_col, value in enumerate(values): item = QtWidgets.QTableWidgetItem(value) # Fix here self.tb_segregados.setItem(row_anchor + index_row, column_anchor + index_col, item) if (event.key() == Qt.Key.Key_C or event.key() == Qt.Key.Key_X) \ and (event.modifiers() & Qt.KeyboardModifier.ControlModifier): copied_cell = sorted(self.tb_segregados.selectedIndexes()) copy_text = "" max_column = copied_cell[-1].column() for cell in copied_cell: cell_item = self.tb_segregados.item(cell.row(), cell.column()) if cell_item: copy_text += cell_item.text() if event.key() == Qt.Key.Key_X: cell_item.setText("") else: copy_text += "" if cell.column() == max_column: copy_text += "\n" else: copy_text += "\t" QApplication.clipboard().setText(copy_text) except Exception as e: print(e) pass |