It's not just that the item text is empty, it's that the item doesn't even have a text property yet. The short answer is to try/catch (check out all the answers to this question)
def _clickedCell(self, item):
print(type(item))
try:
self.text_label.setText(self.table.item(item.row(), item.column()).text())
except AttributeError:
self.text_label.setText('Cell did not have a text property')
except:
self.text_label.setText('Something else went wrong')
But something else surprised me - the item
passed to the _clickedCell
handler is not exactly the QTableWidgetItem
defined, even when it is defined. I've added some print
debugging right before the same try/catch in the short answer.
Here's a smallish app that sets only some QTableWidget item text values and can display a clicked cell text value, or handle the missing text
property:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHeaderView, QFrame,\
QLabel, QTableWidget, \
QTableWidgetItem, QVBoxLayout, QHBoxLayout
class TableWidget(QTableWidget):
def __init__(self):
super().__init__(2,2)
self.setHorizontalHeaderLabels(['Text Set', 'Text Not Set'])
self.setItem(0, 0, QTableWidgetItem("dummy text"))
self.setItem(1, 0, QTableWidgetItem(""))
self.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
class AppDemo(QWidget):
def __init__(self):
super().__init__()
mainLayout = QHBoxLayout()
self.table = TableWidget()
self.table.clicked.connect(self._clickedCell)
mainLayout.addWidget(self.table)
buttonLayout = QVBoxLayout()
self.text_label = QLabel('Initialized value')
self.text_label.setFrameStyle(QFrame.Panel)
self.text_label.setMinimumWidth(70)
self.text_label.setWordWrap(True)
buttonLayout.addWidget(self.text_label)
mainLayout.addLayout(buttonLayout)
self.setLayout(mainLayout)
def _clickedCell(self, item):
print(item.row(), item.column())
print(type(item))
print(type(self.table.item(item.row(), item.column())))
try:
self.text_label.setText(self.table.item(
item.row(), item.column()).text())
except AttributeError:
self.text_label.setText('AttributeError: Cell had no text property')
except:
self.text_label.setText('Something else went wrong')
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
sys.exit(app.exec_())
# from https://learndataanalysis.org/add-copy-remove-rows-on-a-table-widget-pyqt5-tutorial/