Python Forum

Full Version: how to transform pyqt4 code to pyqt5 code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi; I found this code in google, it is written with pyqt4, and I want to adapt it for pyqt5, but I encountered difficulties to fix the errors.

old code with pyqt4 :

import sys, csv
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        for column in range(columns - 1):
            for row in range(rows - 1):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                self.table.setItem(row, column, item)
        self.buttonOpen = QtGui.QPushButton('Open', self)
        self.buttonSave = QtGui.QPushButton('Save', self)
        self.buttonOpen.clicked.connect(self.handleOpen)
        self.buttonSave.clicked.connect(self.handleSave)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        layout.addWidget(self.buttonOpen)
        layout.addWidget(self.buttonSave)

    def handleSave(self):
        path = QtGui.QFileDialog.getSaveFileName(
                self, 'Save File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'wb') as stream:
                writer = csv.writer(stream)
                for row in range(self.table.rowCount()):
                    rowdata = []
                    for column in range(self.table.columnCount()):
                        item = self.table.item(row, column)
                        if item is not None:
                            rowdata.append(
                                unicode(item.text()).encode('utf8'))
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)

    def handleOpen(self):
        path = QtGui.QFileDialog.getOpenFileName(
                self, 'Open File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'rb') as stream:
                self.table.setRowCount(0)
                self.table.setColumnCount(0)
                for rowdata in csv.reader(stream):
                    row = self.table.rowCount()
                    self.table.insertRow(row)
                    self.table.setColumnCount(len(rowdata))
                    for column, data in enumerate(rowdata):
                        item = QtGui.QTableWidgetItem(data.decode('utf8'))
                        self.table.setItem(row, column, item)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window(10, 5)
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())
converted code to pyqt5 :

import sys, csv

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Window(QWidget):
    def __init__(self, rows, columns):
        QWidget.__init__(self)
        self.table = QTableWidget(rows, columns, self)
        for column in range(columns - 1):
            for row in range(rows - 1):
                item = QTableWidgetItem('Text%d' % row)
                self.table.setItem(row, column, item)
        self.buttonOpen = QPushButton('Open', self)
        self.buttonSave = QPushButton('Save', self)
        self.buttonOpen.clicked.connect(self.handleOpen)
        self.buttonSave.clicked.connect(self.handleSave)
        layout = QVBoxLayout(self)
        layout.addWidget(self.table)
        layout.addWidget(self.buttonOpen)
        layout.addWidget(self.buttonSave)

    def handleSave(self):
        path = QFileDialog.getSaveFileName(
                self, 'Save File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'wb') as stream:
                writer = csv.writer(stream)
                for row in range(self.table.rowCount()):
                    rowdata = []
                    for column in range(self.table.columnCount()):
                        item = self.table.item(row, column)
                        if item is not None:
                            rowdata.append(
                                unicode(item.text()).encode('utf8'))
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)

    def handleOpen(self):
        path = QFileDialog.getOpenFileName(
                self, 'Open File', '', 'CSV(*.csv)')
        if not path.isEmpty():
            with open(unicode(path), 'rb') as stream:
                self.table.setRowCount(0)
                self.table.setColumnCount(0)
                for rowdata in csv.reader(stream):
                    row = self.table.rowCount()
                    self.table.insertRow(row)
                    self.table.setColumnCount(len(rowdata))
                    for column, data in enumerate(rowdata):
                        item = QTableWidgetItem(data.decode('utf8'))
                        self.table.setItem(row, column, item)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    window = Window(10, 5)
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())
can you help please to resolve this problem
thanks
change delimiter='\t' in line 37 and line 56 to your delimiter

if your delimiter is comma

delimiter=','

I've changed buttons layout.

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, csv
 
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
 
class Window(QWidget):
    def __init__(self, rows, columns):
        QWidget.__init__(self)
        self.table = QTableWidget(rows, columns, self)
        for column in range(columns - 1):
            for row in range(rows - 1):
                item = QTableWidgetItem('Text%d' % row)
                self.table.setItem(row, column, item)
        self.buttonOpen = QPushButton('Open', self)
        self.buttonOpen.setFixedWidth(100)
        self.buttonSave = QPushButton('Save', self)
        self.buttonSave.setFixedWidth(100)
        self.buttonOpen.clicked.connect(self.handleOpen)
        self.buttonSave.clicked.connect(self.handleSave)
        layout = QVBoxLayout(self)
        layout.addWidget(self.table)
        empty = QWidget()
        btnGroup = QHBoxLayout()
        btnGroup.addWidget(self.buttonOpen)
        btnGroup.addWidget(self.buttonSave)
        btnGroup.addWidget(empty)
        layout.addLayout(btnGroup)
 
    def handleSave(self):
        path,_ = QFileDialog.getSaveFileName(
                self, 'Save File', '', 'CSV(*.csv)')
        if path:
            with open(path, 'w') as stream:
                writer = csv.writer(stream, delimiter='\t')
                for row in range(self.table.rowCount()):
                    rowdata = []
                    for column in range(self.table.columnCount()):
                        item = self.table.item(row, column)
                        if item is not None:
                            rowdata.append(
                                item.text())
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)
 
    def handleOpen(self):
        path,_ = QFileDialog.getOpenFileName(
                self, 'Open File', '', 'CSV Files(*.csv)')
        if path:
            with open(path, 'r') as stream:
                self.table.setRowCount(0)
                self.table.setColumnCount(0)
                for rowdata in csv.reader(stream, delimiter='\t'):
                    row = self.table.rowCount()
                    self.table.insertRow(row)
                    self.table.setColumnCount(len(rowdata))
                    for column, data in enumerate(rowdata):
                        item = QTableWidgetItem(data)
                        self.table.setItem(row, column, item)
 
if __name__ == '__main__':
 
    app = QApplication(sys.argv)
    window = Window(10, 5)
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())
thanks for the correction of the code;
I have another question : how to insert the tablewidget header into the file with this code
https://doc.qt.io/qt-5/classes.html

That can be easily found looking at the documentation -- that is a link to all the documentation -- just look for QWidgetTable then once you get to that look for Header -- fairly easy peasy
(Jan-17-2020, 08:50 PM)atlass218 Wrote: [ -> ]I have another question : how to insert the tablewidget header into the file with this code

copy the first row, set it as headers and delete the first row

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, csv
  
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
  
class Window(QWidget):
    def __init__(self, rows, columns):
        QWidget.__init__(self)
        self.table = QTableWidget(rows, columns, self)
        for column in range(columns):
            for row in range(rows):
                item = QTableWidgetItem('Text%d' % row)
                self.table.setItem(row, column, item)
            header = QTableWidgetItem("Column " + str(column))
            self.table.setHorizontalHeaderItem(column, header)
        self.buttonOpen = QPushButton('Open', self)
        self.buttonOpen.setFixedWidth(100)
        self.buttonSave = QPushButton('Save', self)
        self.buttonSave.setFixedWidth(100)
        self.buttonOpen.clicked.connect(self.handleOpen)
        self.buttonSave.clicked.connect(self.handleSave)
        layout = QVBoxLayout(self)
        layout.addWidget(self.table)
        empty = QWidget()
        btnGroup = QHBoxLayout()
        btnGroup.addWidget(self.buttonOpen)
        btnGroup.addWidget(self.buttonSave)
        btnGroup.addWidget(empty)
        layout.addLayout(btnGroup)
        
  
    def handleSave(self):
        path,_ = QFileDialog.getSaveFileName(
                self, 'Save File', '', 'CSV(*.csv)')
        if path:
            with open(path, 'w') as stream:
                writer = csv.writer(stream, delimiter='\t')
                for row in range(self.table.rowCount()):
                    rowdata = []
                    for column in range(self.table.columnCount()):
                        item = self.table.item(row, column)
                        if item is not None:
                            rowdata.append(
                                item.text())
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)
  
    def handleOpen(self):
        path,_ = QFileDialog.getOpenFileName(
                self, 'Open File', '', 'CSV Files(*.csv)')
        if path:
            with open(path, 'r') as stream:
                self.table.setRowCount(0)
                self.table.setColumnCount(0)
                for rowdata in csv.reader(stream, delimiter='\t'):
                    row = self.table.rowCount()
                    self.table.insertRow(row)
                    self.table.setColumnCount(len(rowdata))
                    for column, data in enumerate(rowdata):
                        item = QTableWidgetItem(data)
                        self.table.setItem(row, column, item)

                self.setHeaders()
            
                
    def setHeaders(self):
        row = 0
        for column in range(self.table.columnCount()):
            if self.table.item(0, column).text() == "":
                newItem = QTableWidgetItem(str(column))
                self.table.setHorizontalHeaderItem(column, newItem)
            else:
                newItem = QTableWidgetItem(self.table.item(0, column))
                self.table.setHorizontalHeaderItem(column, newItem)
                    
        self.table.removeRow(0)
        self.table.resizeColumnsToContents()
 
if __name__ == '__main__':
 
    app = QApplication(sys.argv)
    window = Window(10, 5)
    window.setGeometry(20, 20, 640, 480)
    window.show()
    sys.exit(app.exec_())