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

时间:2020-07-17 03:53:59

标签: python pyqt pyqt5 qtableview qpushbutton

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

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_())

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

非常感谢任何指导。

1 个答案:

答案 0 :(得分:1)

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

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_())