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

Asked

Viewed 491 times

1

How can I get the contents of cell selected in a Grid of the kind QTableView in Python? Follow 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 the Pyqt4 to create the interfaces.

1 answer

1


I believe the best way is:

When someone clicks on the cell, a signal like cellClicked will be issued. Soon, you must 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.