-1

My code is supposed to add data to a two column table when "add" button is clicked. The problem is that when the "add" button is clicked, only the empty row is being added. Can someone please let me know what is wrong? Below is the part of the code that adds data1 and data2 to a table on the right side of the layout. The function add_entry is where the data is being added.

# Import dependencies
from PyQt5.QtWidgets import (QWidget, QApplication, QTableWidget, QTableWidgetItem,QHBoxLayout, QVBoxLayout, QHeaderView, QPushButton, QDialog,
                            QLabel, QFileDialog, QMainWindow, QAction, QLineEdit)
from PyQt5.Qt import Qt
from PyQt5.QtGui import QPainter
from PyQt5.QtChart import QChart, QChartView, QLineSeries
import sys
import pandas as pd
import math

# ------------------------------------------------------UI-main----------------------------------------------------------------------------------
# Creates a QApplication instance
class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        
        self.items=0

        # Creates table on the left size
        self.table_l = QTableWidget()
        self.table_l.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        
        # Creates layout object for the right side
        self.layoutRight = QVBoxLayout()
        
        # Creates chart widget
        self.chartView = QChartView()
        # Smooths the edge of the chart
        self.chartView.setRenderHint(QPainter.Antialiasing)

       # Creates table on the right size
        self.table_r = QTableWidget()
        self.table_r.setColumnCount(2)
        # self.table_r.setRowCount()
        self.table_r.setHorizontalHeaderLabels(('Data1', 'Data2'))
        self.table_r.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table_r.setMaximumSize(600, 300)

        self.lineEditData1 = QLineEdit()
        self.lineEditData2 = QLineEdit()
        
        # Create push buttons
        self.buttonAdd = QPushButton('Add')
        self.buttonClear = QPushButton('Clear')
        self.buttonQuit = QPushButton('Quit')

        self.buttonAdd.setEnabled(False)

        self.layoutRight.setSpacing(10)
        self.layoutRight.addWidget(self.table_r, 50)
        self.layoutRight.addWidget(QLabel('data1'))
        self.layoutRight.addWidget(self.lineEditData1)
        self.layoutRight.addWidget(QLabel('data2'))
        self.layoutRight.addWidget(self.lineEditData2)
        self.layoutRight.addWidget(self.buttonAdd)
        
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.table_l, 50)
        self.setLayout(self.layout)
        self.layout.addLayout(self.layoutRight, 50)
        
        # Connect button to function functions
        self.buttonQuit.clicked.connect(lambda:app.quit())
        self.buttonAdd.clicked.connect(self.add_entry)
        self.buttonClear.clicked.connect(self.reset_table)

        self.lineEditData1.textChanged[str].connect(self.check_disable)
        self.lineEditData2.textChanged[str].connect(self.check_disable)
    
    def add_entry(self):
        Data1 = self.lineEditData1.text()
        Data2 = self.lineEditData2.text()
        
        try:
            Data1Item = QTableWidgetItem(int(Data1))
            Data2Item = QTableWidgetItem(float(Data2))
            Data2Item.setTextAlignment(Qt.AlignRight | Qt.AlignCenter)
            
            self.table_r.insertRow(self.items)
            self.table_r.setItem(self.items, 0, Data1Item)
            self.table_r.setItem(self.items, 1, Data2Item)
            
            self.items +=1

            # after passing the item, clear the field by entering an empty string
            self.lineEditData1.setText('')
            self.lineEditData2.setText('')
        except ValueError:
            pass

# Creates main window object instance
class MainWindow(QMainWindow):
    def __init__(self, widget):
        super().__init__()
        self.setWindowTitle('test')

        self.resize(1200, 1200)

        self.menuBar = self.menuBar()
        self.fileMenu = self.menuBar.addMenu('File')

        # import wind speed data
        importAction = QAction('Open File', self)
        importAction.setShortcut('Ctrl+O')

        # exit action
        exitAction = QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(lambda: app.quit())

        self.fileMenu.addAction(importAction)
        self.fileMenu.addAction(exitAction)

        self.setCentralWidget(widget)

if __name__ =='__main__':
    # don't auto scale when drag app to a different monitor
    #QGuiApplication.setHightDpiScaleFactorRoundingPolicy(Qt.HightDpiScaleFactorRoundingPolicy.PassThrough)
    
    app = QApplication(sys.argv)

    w = MyApp()
    demo = MainWindow(w)
    demo.show()
    try:
        sys.exit(app.exec())
    except SystemExit:
        print('Closing window...')
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

1

The objective of exceptions is not to hide errors but to know how to prevent them, so they must be as small as possible so as not to hide other errors. In this case, QTableWidgetItem accepts a string as an argument and not numerical values, therefore an exception is thrown preventing the code that adds the items from being executed. The solution is to use the setData() method of the QTableWidgetItem:

def add_entry(self):
    data1 = self.lineEditData1.text()
    data2 = self.lineEditData2.text()

    try:
        value1 = int(data1)
        value2 = float(data2)
    except ValueError:
        print("failed conversion")
        return
    else:
        data1_item = QTableWidgetItem()
        data1_item.setData(Qt.DisplayRole, value1)
        data2_item = QTableWidgetItem()
        data2_item.setData(Qt.DisplayRole, value2)
        data2_item.setTextAlignment(Qt.AlignRight | Qt.AlignCenter)

        row = self.table_r.rowCount()
        self.table_r.insertRow(row)
        self.table_r.setItem(row, 0, data1_item)
        self.table_r.setItem(row, 1, data2_item)
        self.lineEditData1.clear()
        self.lineEditData2.clear()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241