Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get cell value based on header string and selected row

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.

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?

like image 618
panofish Avatar asked May 03 '13 20:05

panofish


2 Answers

If you do that you got: "local variable 'matchcol' referenced before assignment"

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
like image 165
panofish Avatar answered Nov 15 '22 11:11

panofish


Once you have the row and column of the cell, you can use QTableWidget.item to get the QTableWidgetItem, from which you can get the text and/or the stored data.

So in your slot, if you have row and column, you can see which letter this column corresponds to, and from there determine which column you want to get the data from.

like image 38
jadkik94 Avatar answered Nov 15 '22 10:11

jadkik94