Reputation: 25370
I have a piece of code that produces a table and allow you to input data as required. The table is shown below:
What is actually being inputted into the table is not always temperature and voltage and rather than each time I run through the code having to go and change the column headers, it would be nice if I could do it after the table is plotted by clicking on it.
I thought this might be done automatically as I can click on the table and change the values even after using the 'insert into table' button.
So my question is, how do I change the column headers by clicking on them?
My code is below:
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.table = QtGui.QTableWidget(self)
self.table.setRowCount(0)
self.table.setColumnCount(2)
self.textInput1 = QtGui.QLineEdit()
self.textInput2 = QtGui.QLineEdit()
self.button = QtGui.QPushButton("Insert into table")
self.button.clicked.connect(self.populateTable)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.table)
layout.addWidget(self.textInput1)
layout.addWidget(self.textInput2)
layout.addWidget(self.button)
self.table.setHorizontalHeaderLabels(("Temperatures;Voltages").split(";"))
def populateTable(self):
text1 = self.textInput1.text()
text2 = self.textInput2.text()
row = self.table.rowCount()
self.table.insertRow(row)
self.table.setItem(row, 0, QtGui.QTableWidgetItem(text1))
self.table.setItem(row, 1, QtGui.QTableWidgetItem(text2))
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(400, 100, 550, 450)
window.show()
sys.exit(app.exec_())
Upvotes: 0
Views: 64
Reputation: 1044
You could connect the header's sectionDoubleClicked
and rename the relevant header using setText
.
connect the header's sectionDoubleClicked to a function:
self.table.horizontalHeader().sectionDoubleClicked.connect(self.renameHeader)
get user-input for a new title and rename:
def renameHeader(self, index):
oldHeader = self.table.horizontalHeaderItem(index).text()
newHeader, confirm = QtGui.QInputDialog.getText(self,
'Rename Header',
'',
QtGui.QLineEdit.Normal,
oldHeader)
if confirm:
self.table.horizontalHeaderItem(index).setText(newHeader)
Upvotes: 1