根据标题字符串和选定行获取单元格值 [英] get cell value based on header string and selected row
问题描述
例如,我有一个 PyQt QTableWidget,它有 3 列和 2 行.列标题标记为 A、B 和 C.
For example, I have a PyQt QTableWidget which has 3 columns and 2 rows. The column headers are labeled A, B, and C.
A B C
1 2 3
4 5 6
这是我当前来源的摘录:
This is the excerpt from my current source:
class myform(QtGui.QMainWindow):
def __init__(self, parent=None):
super(myform, self).__init__(parent)
self.ui = Ui_mygui()
self.ui.setupUi(self)
self.ui.mytablewidget.cellClicked.connect(self.cell_was_clicked)
@QtCore.pyqtSlot() # prevents executing following function twice
def cell_was_clicked(self):
row = self.ui.mytablewidget.currentItem().row()
print "row=",row
col = self.ui.mytablewidget.currentItem().column()
print "col=",col
item = self.ui.mytablewidget.horizontalHeaderItem(col).text()
print "item=",item
我的代码有效,当我在表格中选择一行时..我从选择中获得了正确的行号和列号.
My code works and when I select a row in my table.. I get the correct row and col numbers from the selection.
返回给定标题名称的选定行的单元格值所需的代码是什么?如果我选择第 2 行单元格 1 ...如何在同一行上获得 C 列的单元格值?
What is the code needed to return a cell value for the selected row given a specified header name? If I select row 2 cell 1 ... how can I get the cell value of column C on the same row?
推荐答案
如果你这样做了,你会得到:在赋值之前引用了局部变量 'matchcol'"
If you do that you got: "local variable 'matchcol' referenced before assignment"
要解决您应该在 if 循环中返回单元格的问题:
To fix that you should return the cell inside if loop:
#===================================================================
# given a tablewidget which has a selected row...
# return the column value in the same row which corresponds to a given column name
# fyi: columnname is case sensitive
#===================================================================
def getsamerowcell(widget,columnname):
row = widget.currentItem().row()
# col = widget.currentItem().column()
# loop through headers and find column number for given column name
headercount = widget.columnCount()
for x in range(headercount):
headertext = widget.horizontalHeaderItem(x).text()
if columnname == headertext:
cell = widget.item(row, x).text() # get cell at row, col
return cell
这篇关于根据标题字符串和选定行获取单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!