I have created a Qtablewidget as a class, and add_button to add rows, a delete_button to remove rows from table down upwards. I would like to connect functions to buttons, but it doesn't work correctly. I have used getattr method to call the function, still does not work.
The table
to explain more, those scriptlines are giving attributte errors. when they are called by button.clicked.connect method.
add_button.clicked.connect(self._addrow)
delete_button.clicked.connect(self._removeItem)
The script is as below:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
class loadtable(QtWidgets.QTableWidget):
def __init__(self, parent=None):
super(loadtable, self).__init__(parent)
self.setColumnCount(5)
self.setRowCount(1)
self.setFont(QtGui.QFont("Helvetica", 10, QtGui.QFont.Normal, italic=False))
headertitle = ("A","B","C","D","E")
self.setHorizontalHeaderLabels(headertitle)
self.verticalHeader().setVisible(False)
self.horizontalHeader().setHighlightSections(False)
self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)
self.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
self.setColumnWidth(0, 130)
combox_lay = QtWidgets.QComboBox(self)
combox_lay.addItems(["I","II"])
self.setCellWidget(0, 4, combox_lay)
self.cellChanged.connect(self._cellclicked)
#self.cellChanged.connect(self._addrow)
#self.cellDoubleClicked.connect(self._removerow)
def _cellclicked(self):
self.value = self.currentItem()
self.value.setTextAlignment(Qt.AlignCenter)
#if self.value is not None:
#return self.value.setTextAlignment(Qt.AlignCenter)
def _addrow(self):
rowcount = self.rowCount()
print(rowcount)
self.setRowCount(rowcount+1)
combox_add = QtWidgets.QComboBox(self)
combox_add.addItems(["I","II"])
self.setCellWidget(rowcount, 4, combox_add)
def _removerow(self):
self.removeRow(1)
class thirdtabloads(QtWidgets.QWidget):
def __init__(self, parent=None):
super(thirdtabloads, self).__init__(parent)
table = loadtable()
button_layout = QtWidgets.QVBoxLayout()
add_button = QtWidgets.QPushButton("Add")
add_button.clicked.connect(self._addrow)
delete_button = QtWidgets.QPushButton("Delete")
delete_button.clicked.connect(self._removeItem)
button_layout.addWidget(add_button, alignment=QtCore.Qt.AlignBottom)
button_layout.addWidget(delete_button, alignment=QtCore.Qt.AlignTop)
tablehbox = QtWidgets.QHBoxLayout()
tablehbox.setContentsMargins(10,10,10,10)
tablehbox.addWidget(table)
grid = QtWidgets.QGridLayout(self)
grid.addLayout(button_layout, 0, 1)
grid.addLayout(tablehbox, 0, 0)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = thirdtabloads()
w.show()
sys.exit(app.exec_())