Issue
Basically I have a delete button for each row in a QTableWidget for the click event.
How do I find the row index of that particular button that get clicked?
class WidgetGallery(QDialog):
def __init__(self, parent=None):
super(WidgetGallery, self).__init__(parent)
self.table = QTableWidget(10, 3)
col_1 = QTableWidgetItem("first_col")
col_2 = QTableWidgetItem("second_col")
deleteButton = QPushButton("delete_this_row")
deleteButton.clicked.connect(self.deleteClicked)
self.table.setItem(0, 0, col_1)
self.table.setItem(0, 1, col_2)
self.table.setCellWidget(0, 2, deleteButton)
self.mainLayout = QGridLayout()
self.mainLayout.addWidget(self.table)
def deleteClicked(self):
sender = self.sender()
row = sender.parent().........?
Solution
Based on your comments, you are using my previous answer as a basis, but as you point out these are failing because the context of the previous question differs from your current code, in the previous case there is a parent widget where the button is set, and that widget is just set in the QTableWidget. In this case, it must be direct:
from PyQt5 import QtCore, QtGui, QtWidgets
class WidgetGallery(QtWidgets.QDialog):
def __init__(self, parent=None):
super(WidgetGallery, self).__init__(parent)
self.table = QtWidgets.QTableWidget(10, 3)
col_1 = QtWidgets.QTableWidgetItem("first_col")
col_2 =QtWidgets.QTableWidgetItem("second_col")
deleteButton = QtWidgets.QPushButton("delete_this_row")
deleteButton.clicked.connect(self.deleteClicked)
self.table.setItem(0, 0, col_1)
self.table.setItem(0, 1, col_2)
self.table.setCellWidget(0, 2, deleteButton)
self.mainLayout = QtWidgets.QGridLayout(self)
self.mainLayout.addWidget(self.table)
@QtCore.pyqtSlot()
def deleteClicked(self):
button = self.sender()
if button:
row = self.table.indexAt(button.pos()).row()
self.table.removeRow(row)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = WidgetGallery()
w.show()
sys.exit(app.exec_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.