如何检测 QTableView 行单元格中的按钮单击

How to detect a button click in a QTableView rows cell

我能够在 QtableView 单元格中插入 PushButton

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QTableView, QPushButton, QAbstractItemView
from PyQt5.QtGui import QStandardItemModel, QStandardItem


app = QApplication(sys.argv)
app.setStyle("experiment")
tab = QTableView()
sti = QStandardItemModel()
for idx in range(0,3):
    sti.appendRow([QStandardItem(str(i)) for i in range(4)])
    tab.setModel(sti)
    tab.setEditTriggers(QAbstractItemView.NoEditTriggers)
    tab.setIndexWidget(sti.index(idx, 3), QPushButton("button"))
tab.show()
sys.exit(app.exec_())

我如何检查/检测是否按下了单元格按钮?

非常感谢任何指导。

您必须连接按钮的点击信号:

from functools import partial
import sys

from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QApplication, QTableView, QPushButton, QAbstractItemView


app = QApplication(sys.argv)
app.setStyle("experiment")
tab = QTableView()
tab.setEditTriggers(QAbstractItemView.NoEditTriggers)
sti = QStandardItemModel()
tab.setModel(sti)


def on_clicked(index):
    print("clicked", index)


for idx in range(0, 3):
    sti.appendRow([QStandardItem(str(i)) for i in range(4)])
    btn = QPushButton("button")
    btn.clicked.connect(partial(on_clicked, idx))
    tab.setIndexWidget(sti.index(idx, 3), btn)

tab.show()
sys.exit(app.exec_())