如何将多个 QPushButton 添加到 QTableView? [英] How to add multiple QPushButtons to a QTableView?
问题描述
我有一个 QTableView
,我想为每一行设置一个 QPushButton
.我在从 QWidget
派生的类中按以下方式执行此操作,以下示例在 herehere一个>:
I have a QTableView
to which I want to set a QPushButton
for every row. I am doing this as follows within my class derived from QWidget
following an example found here:
for index in range(number_rows):
btn_sell = QPushButton("Edit", self)
btn_sell.clicked.connect(self.button_edit)
table_view.setIndexWidget(table_view.model().index(index, 4), btn_sell)
如果绘制了表格并且我单击了 QPushButton
之一,则调用方法 self.button_edit
- 但是哪个?似乎没有给 self.button_edit
提供任何类型的事件",那么我如何找到在其中单击的 QPushButton
的行索引button_edit
方法?
If the table is drawn and I click on one of the QPushButton
the method self.button_edit
is called - but which one? It does not seem that an 'event' of any sort is given to self.button_edit
, so how can I find the row-index of the QPushButton
that was clicked within the button_edit
method?
也许有一种完全不同的方法可以为表格的每一行添加一个按钮?
Maybe there is a different way altogether to add a button to each row of a table?
推荐答案
您的事件处理程序将类似于:
Your event handler will look similar to this:
def handleButtonClicked(self):
button = QtGui.qApp.focusWidget()
# or button = self.sender()
index = self.table.indexAt(button.pos())
if index.isValid():
print(index.row(), index.column())
这使用 indexAt
获取按钮位置的函数.
This uses the indexAt
function to get the button's position.
为清楚起见,我的脚本如下所示:
For clarity, my script looks like this:
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self,parent)
self.table = QtGui.QTableWidget()
self.table.setColumnCount(3)
self.setCentralWidget(self.table)
data1 = ['row1','row2','row3','row4']
data2 = ['1','2.0','3.00000001','3.9999999']
self.table.setRowCount(4)
for index in range(4):
item1 = QtGui.QTableWidgetItem(data1[index])
self.table.setItem(index,0,item1)
item2 = QtGui.QTableWidgetItem(data2[index])
self.table.setItem(index,1,item2)
self.btn_sell = QtGui.QPushButton('Edit')
self.btn_sell.clicked.connect(self.handleButtonClicked)
self.table.setCellWidget(index,2,self.btn_sell)
def handleButtonClicked(self):
button = QtGui.qApp.focusWidget()
# or button = self.sender()
index = self.table.indexAt(button.pos())
if index.isValid():
print(index.row(), index.column())
这将产生一个像这样的小图形用户界面:
Which will produce a small GUI like this:
当 Edit
按钮被点击时,它会打印到控制台:
When the Edit
buttons are clicked, it prints, to the console:
(0, 2)
(1, 2)
(2, 2)
(3, 2)
第一个元素是您的行索引,第二个是您的列(请记住它是基于 0 的,这就是为什么它显示 2,而不是 3 - 尽管有列标题).
The first element is your row index, the second is your column (remember it is 0 based, which is why it shows 2, not 3 - despite the column headers).
这篇关于如何将多个 QPushButton 添加到 QTableView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!