Search code examples
pythonpyqtpyqt5qtableview

How to get data from QTableView by pressing Enter Key in PyQt5


I'm making an app with PyQt5 and facing some troubles. I want to select data from QTableView by pressing Enter key and display it in QLineEdit. I've done these things with doubleClicked signals but I still want to display data to QLineEdit by both 2 ways and then close QTableView dialog right after pressing Enter key or double clicking. Here is my code:

import sys 
import os
from PyQt5 import QtCore, QtGui, QtWidgets, uic


class Application(QtWidgets.QMainWindow):
    def __init__(self):
        super(Application, self).__init__()
        self.mainwindow = uic.loadUi('test.ui', self)

        self.mainwindow.pushButton.clicked.connect(self.table)

    def table(self):
        self.table = QtWidgets.QTableView()

        data = [
            [2, 3, 5], 
            [23, 4, 5],
            [2, 6, 7],
            [0, 3, 5]
        ]

        self.model = TableModel(data)
        self.table.setModel(self.model)

        self.table.doubleClicked.connect(self.on_click)

        self.table.show()

    def on_click(self, signal):
        row = signal.row()  # RETRIEVES ROW OF CELL THAT WAS DOUBLE CLICKED
        column = signal.column()  # RETRIEVES COLUMN OF CELL THAT WAS DOUBLE CLICKED
        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: {}\n'.format(row, column, cell_value))

        self.mainwindow.lineEdit.setText('%s' %cell_value)

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super(TableModel, self).__init__()
        self._data = data

    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            return self._data[index.row()][index.column()]

    def rowCount(self, index):

        return len(self._data)

    def columnCount(self, index):

        return len(self._data[0])

if __name__ == '__main__':
    application = QtWidgets.QApplication(sys.argv)
    window = Application()
    window.show()
    application.exec_()

And my Gui:

enter image description here

Lets me explain a little bit: when click on pushbutton, it shows up a data table, and then I want to select data in the table by pressing enter key, after that it will display data into QlineEdit and close the table


Solution

  • The logic is to detect the keypress, for example using an eventFilter, and then obtain the QModelIndex of the selected element:

    class Application(QtWidgets.QMainWindow):
        def __init__(self):
            super(Application, self).__init__()
            uic.loadUi("test.ui", self)
    
            self.pushButton.clicked.connect(self.table)
    
            self.table = QtWidgets.QTableView()
            self.table.doubleClicked.connect(self.write_text)
            self.table.installEventFilter(self)
    
        def table(self):
            data = [[2, 3, 5], [23, 4, 5], [2, 6, 7], [0, 3, 5]]
            self.model = TableModel(data)
            self.table.setModel(self.model)
            self.table.show()
    
        def write_text(self, index):
            row, column, cell_value = index.row(), index.column(), index.data()
            print("Row {}, Column {} clicked - value: {}".format(row, column, cell_value))
            self.lineEdit.setText("%s" % cell_value)
            self.table.close()
    
        def eventFilter(self, obj, event):
            if obj is self.table and event.type() == QtCore.QEvent.KeyPress:
                if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
                    indexes = self.table.selectedIndexes()
                    if indexes:
                        self.write_text(indexes[0])
            return super(Application, self).eventFilter(obj, event)