开发者社区> 问答> 正文

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

一码平川MACHEL 2019-01-23 15:00:43 1701

所以基本上我有一个删除按钮,用于点击事件的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().........?
索引
分享到
取消 提交回答
全部回答(1)
  • 一码平川MACHEL
    2019-07-17 23:26:39

    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_())
    1 0
+ 订阅

时时分享云计算技术内容,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

推荐文章
相似问题