开发者社区> 问答> 正文

pyqt5按钮如何删除它所在的QTableWidget中的行

所以基本上我有一个删除按钮,用于点击事件的QTableWidget中的每一行。

如何找到被点击的特定按钮的行索引?

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().........?

展开
收起
一码平川MACHEL 2019-01-23 15:00:43 9380 0
1 条回答
写回答
取消 提交回答
  • 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_())
    2019-07-17 23:26:39
    赞同 2 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载