-1

I'm writing a GUI that analysis CSV files and I want to implement a function where the row will be deleted only when the whole row is selected. My current problem is when I select a cell and hit backspace, the row in which the selected cell located will be deleted as well. how do I prevent this?

from GUI import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import Qt
from PyQt5.QtCore import QItemSelectionModel
from PyQt5.QtWidgets import (QApplication,QMainWindow,QFileDialog,QTableWidget,
                             QMessageBox,QTableWidgetItem,QHeaderView)

class mainForm(QMainWindow,Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.initUI()

     def keyPressEvent(self, event):
        if event.key() == Qt.Key_Backspace:
            self.removeRow()
    
     def selectedRow(self):
        if self.tabWidget.currentIndex() is 0 and self.inLoanTable.selectionModel().hasSelection():
            row = self.inLoanTable.selectionModel().selectedIndexes()[0].row()
            return int(row)

     def removeRow(self):
        if self.tabWidget.currentIndex() is 0 and self.inLoanTable.rowCount() > 0:
            row = self.selectedRow()
Alex
  • 3
  • 3

1 Answers1

1

I did like this in my code. It runs when button pressed. You can bind it with backspace.

def deleteItem(self):
   model_index = self.tableWidget.selectionModel().selectedRows()
   index = QtCore.QPersistentModelIndex(model_index)
   self.tableWidget.remoweRow(index.row())

If you want to delete multiple rows you can do it like this too.

def deleteItem(self):
   index_list = []
   for model_index in self.tableWidget.selectionModel().selectedRows()
       index = QtCore.QPersistentModelIndex(model_index)
       index_list.append(index)
   for index in index_list:
       self.tableWidget.remoweRow(index.row())
Jiraiya
  • 101
  • 1
  • 9
  • thanks, but it gives me an error:AttributeError: 'builtin_function_or_method' object has no attribute 'selectedRows' – Alex Jul 21 '20 at 06:36
  • sorry it should be selectionModel().selectedRows() try it like that – Jiraiya Jul 21 '20 at 07:51
  • File "/Users/yayuni/Desktop/HerbariumGUI/main.py", line 287, in testDRow index = QtCore.QPersistentModelIndex(modelIndex) TypeError: arguments did not match any overloaded call: QPersistentModelIndex(): too many arguments QPersistentModelIndex(QModelIndex): argument 1 has unexpected type 'list' QPersistentModelIndex(QPersistentModelIndex): argument 1 has unexpected type 'list' – Alex Jul 21 '20 at 07:54