How to get the contents of the selected cell in the Grid QTableView in Python?

1

How can I get the content of the cell selected in a Grid of type QTableView in Python ? Here is the code below:

__author__ = 'Dener'

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class Model(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items = ['Row0_Column0','Row0_Column1','Row0_Column2']

    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable

    def rowCount(self, parent):
        return 1
    def columnCount(self, parent):
        return len(self.items)

    def data(self, index, role):
        if not index.isValid(): return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()

        column=index.column()
        if column<len(self.items):
            return QVariant(self.items[column])
        else:
            return QVariant()

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)

        tablemodel=Model(self)

        self.tableview=QTableView()
        self.tableview.setModel(tablemodel)
        self.tableview.clicked.connect(self.viewClicked) #Define o evento clique.

        #self.tableview.setSelectionBehavior(QTableView.SelectRows)

        layout = QHBoxLayout(self)
        layout.addWidget(self.tableview)

        self.setLayout(layout)

    def viewClicked(self, clickedIndex):
        row = clickedIndex.row()
        model = clickedIndex.model()
        print 'Clique ', self.retorna()

    def retorna(self): #Funcao que estou usando para retonar o conteudo da celula selecionada. Sem sucesso.
        index = self.tableview.selectedIndexes()[0]
        id_us = int(self.tableview.model().data(index).toString())
        return str(id_us)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    print w.retorna()
    w.show()
    sys.exit(app.exec_())

I'm using PyQt4 to create the interfaces.

    
asked by anonymous 02.09.2015 / 01:01

1 answer

1

I believe the best way is:

When someone clicks the cell, a cellClicked type sign will be issued. So you should connect to this signal:

connect(ui.tableWidget, SIGNAL(cellClicked(int,int)), this, SLOT(myCellClicked(int,int)));

And implement the myCellClicked function to store which cell was selected. Later you can use the model, when necessary, to return the value of this cell.

    
02.09.2015 / 07:03