'how to make a cell in a QTableWidget read only?
i have the following code defining the gui of my app
class Ui (object):
def setupUi():
self.tableName = QtGui.QTableWidget(self.layoutWidget_20)
self.tableName.setObjectName(_fromUtf8("twHistoricoDisciplinas"))
self.tableName.setColumnCount(4)
self.tableName.setRowCount(3)
and the following code in my app
class MainWindow(QtGui.QMainWindow):
def __init__(self):
self.ui = Ui()
self.ui.setupUi(self)
self.createtable()
#creating a tw cell
def cell(self,var=""):
item = QtGui.QTableWidgetItem()
item.setText(var)
return item
def createtable(self):
rows = self.tableName.rowCount()
columns = self.tableName.columnCount()
for i in range(rows):
for j in range(columns):
item = self.cell("text")
self.ui.tableName.setItem(i, j, item)
I want to be able to add new rows and columns and edit them but i want to lock some of the cells. ( i already have code that expand the table ) how can i make some cells read only while keeping the others read write? i found this link How to make a column in QTableWidget read only? with a solution for the problem in C++, is python solution similar ?
EDIT: Removed the answer from the post and pasted as an answer
Solution 1:[1]
The editing status of a QTableWidgetItem is never entered when there are no Edit Triggers:
self.tableName.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
Solution 2:[2]
Like Sven Krüger's answer, you can also use this methods for PyQt5:
self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
Solution 3:[3]
If you want the UI to look the same (have it still selectable, and turn blue, but just not editable) I found QtCore.Qt.ItemIsEditable gave good results.
item = QtWidgets.QTableWidgetItem()
item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
self.table_widget.setItem(row, column, item)
Solution 4:[4]
For PyQt6, it's the same as @ozcanyarimdunya but with the enum EditTrigger:
self.tableWidget.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sven Krüger |
| Solution 2 | ozcanyarimdunya |
| Solution 3 | Adam Sirrelle |
| Solution 4 | Jordan Choquet -boreas |
