I am using QStandardItemModel for my qtableview.
import ui_my_viewlogs
import os
from PyQt4 import QtCore, QtGui
class my_viewlogs(QtGui.QDialog, ui_my_viewlogs.Ui_viewlogs):
def __init__(self):
super(my_viewlogs, self).__init__()
self.setupUi(self)
self.model = QtGui.QStandardItemModel()
self.tableView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.header_names = ['abc', 'def', 'ghi', 'kjl', 'mno', 'pqr']
self.model.setHorizontalHeaderLabels(self.header_names)
self.tableView.verticalHeader().setVisible(False)
self.tableView.setShowGrid(False)
self.selectionModel = self.tableView.selectionModel()
self.tableView.customContextMenuRequested.connect(self.open_menu)
self.tableView.setModel(self.model)
self.tableView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
def open_menu(self, position):
menu = QtGui.QMenu()
remove_selected_item_icon = QtGui.QIcon()
remove_selected_item_icon.addPixmap(QtGui.QPixmap(":/images /Images/deleteSelected.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
remove_selected_item = menu.addAction(remove_selected_item_icon, "Remove selected item(s) ")
if action == remove_selected_item:
model = self.model
indices = self.tableView.selectionModel().selectedRows()
for index in sorted(indices):
model.removeRow(index.row(), QtCore.QModelIndex())
here when I am trying to delete the row selected(i.e. model.removeRow() ) I am getting a error" TypeError: argument 1 of QAbstractItemModel.removeRow() has an invalid type".
I have searched a lot for the correct way of deleting a selected row/rows in qtableview of pyqt. However, I am not able to delete the selected row/rows.
Can you please share a sample code for deleting selected row/rows in qtableview of pyqt?
the method model.removeRow(index.row()) removes the row selected.
model = self.model
indices = self.tableView.selectionModel().selectedRows()
for index in sorted(indices):
model.removeRow(index.row())
in the indices variable we get the selected row, then we delete the row.
For deleting multiple rows in our selection of tableview:
index_list = []
for model_index in self.tableView.selectionModel().selectedRows():
index = QtCore.QPersistentModelIndex(model_index)
index_list.append(index)
for index in index_list:
self.model.removeRow(index.row())