Pyqt5. How to get selected column name from qtable
时间: 2025-02-11 17:40:23 浏览: 29
When using PyQt5 with a QTableWidget, if you want to retrieve the name of the selected column, you can use the `currentItem()` function to access the current item in the table and then its `data()` method along with `column` attribute to obtain the data and column index. Here's an example:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem
class TableSelectionExample(QWidget):
def __init__(self):
super().__init__()
self.table = QTableWidget()
self.init_table()
layout = QVBoxLayout()
layout.addWidget(self.table)
self.setLayout(layout)
def init_table(self):
headers = ["Column 1", "Column 2", "Column 3"]
self.table.setColumnCount(len(headers))
self.table.setHorizontalHeaderLabels(headers)
for i in range(10): # Example data
row = []
for j, header in enumerate(headers):
item = QTableWidgetItem(f"Row {i}, Column {j+1}")
row.append(item)
self.table.setRow(i, row)
def select_and_get_column_name(self):
current_item = self.table.currentItem()
if current_item:
column_index = current_item.column()
column_name = self.table.horizontalHeaderItem(column_index).text()
return column_name
if __name__ == "__main__":
app = QApplication([])
ex = TableSelectionExample()
ex.show()
selected_column = ex.select_and_get_column_name()
print(f"The selected column name is: {selected_column}") # Replace this line with your desired action after getting the column name
app.exec_()
```
In this code snippet, we create a simple QTableWidget, fill it with some sample data, and define a method `select_and_get_column_name()` that retrieves the selected column name when a cell is clicked or selected.
Remember to install and properly import the necessary modules for PyQt5, as shown in the provided error message[^1]. If you're still encountering issues with importing, make sure you have PyQt5 installed correctly and the environment is set up accordingly.
阅读全文
相关推荐













