A
A
Alexander2020-02-29 13:45:50
Python
Alexander, 2020-02-29 13:45:50

How to return cell index in QTableView?

I'm learning PyQT5 (unfortunately, I can't find a tutorial, so I'm struggling with a dry manual with a small number of examples).
I create a QTableView filled with random data, and immediately try to print to the console the index of the cell that contains "7".
No matter how hard I tried, nothing came out.
The output is: [].
And how to convert to a cell index I can not understand in any way.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import random
 
 
class Splash(QWidget):
    def __init__(self):
        super().__init__()
 
        self.table = QTableView(self) 
        self.table.setMinimumWidth(302)
        self.table.setGeometry(0, 0, 575, 575)
        self.model = QStandardItemModel(self)
        self.table.setModel(self.model)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.populate()
 
        self.table.doubleClicked.connect(self.on_click)
 
    def on_click(self, signal):
        row = signal.row()
        column = signal.column()
        cell_dict = self.model.itemData(signal)  # RETURNS DICT VALUE OF SIGNAL
        cell_value = cell_dict.get(0)  # RETRIEVE VALUE FROM DICT
        
        index = signal.sibling(row, 0)
        index_dict = self.model.itemData(index)
        index_value = index_dict.get(0)
        print(
            'Row {}, Column {} clicked - value: {}\nColumn 1 contents: {}'.format(row, column, cell_value, index_value))
 
    def populate(self):
        values = []
        for i in range(10):
            sub_values = []
            for i in range(4):
                value = random.randrange(1, 10)
                sub_values.append(value)
            values.append(sub_values)
 
        for value in values:
            row = []
            for item in value:
                cell = QStandardItem(str(item))
                row.append(cell)
            self.model.appendRow(row)

        self.show()

        print(self.model.findItems('7')) #ВОТ ТУТ ПЫТАЮСЬ ВЫВЕСТИ ПРИНТ.

 
if __name__ == '__main__':
    import sys
 
    app = QApplication(sys.argv)
    ex = Splash()
    sys.exit(app.exec_())

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-03-01
@Ic2d

item = self.model.findItems('7')[0]
print(item.row())

It turned out that an array is returned. Google confused me because people wrote that it returns only the first found element (and I need the first found element)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question