简体   繁体   English

QTableWidget选择一个带有按钮的单元格

[英]QTableWidget select a cell with a button in it

I have a question regarding QTableWidget at PyQt4. 我对PyQt4的QTableWidget有疑问。 Say I have a QTableWidget, where I want to have an event connected to a cell click using: 假设我有一个QTableWidget,我想在其中使用以下命令将事件连接到单元格单击:

table.cellClicked.connect(cellClick)

then, cellClick function does its job. 然后, cellClick函数完成其工作。 The thing is: some cells contain a button, like so (coordinates 0,0 as an example): 关键是:有些单元格包含一个按钮,例如这样(例如,坐标0,0):

button = QtGui.QPushButton()
table.setCellWidget(0,0, button)

Now comes my problem. 现在是我的问题。 The presence of the button in a cell (which takes up the entire cell space) completely disables the cellClicked - the cell doesn't get clicked, the action can't be detected. 单元格中的按钮(占用整个单元格空间)的存在会完全禁用cellClicked-单元格不会被单击,因此无法检测到该操作。 But I do want my button to fill the cell. 但是我确实希望我的按钮充满整个单元格。

So, in short, my question is - how can I select (click) a QTableWidget cell when there's a button inside it? 简而言之,我的问题是-当内部有一个按钮时,如何选择(单击)QTableWidget单元格?

The simple answer would seem to be: 简单的答案似乎是:

    button.clicked.connect(cellClick)

But then how would you know the row/column of the cell that was clicked? 但是,您怎么知道被单击的单元格的行/列呢? So the next iteration might be: 因此,下一个迭代可能是:

    button = QtGui.QPushButton()
    table.setCellWidget(row, column, button)
    button.clicked.connect(
        lambda *args, row=row, column=column: cellClick(row, column))

Which is okay if the table is static. 如果表是静态的,那没关系。 But what if the rows and columns can be rearranged? 但是如果行和列可以重新排列怎么办? The row/column cached in the button's clicked handler could be invalidated in that case. 在这种情况下,按钮的clicked处理程序中缓存的行/列可能无效。 So the next iteration might be: 因此,下一个迭代可能是:

   index = QtCore.QPersistentModelIndex(table.model().index(row, column))
   button.clicked.connect(
        lambda *args, index=index: cellClick(index.row(), index.column()))

(NB: you can connect other slots to the button's clicked signal, but the order they will be invoked in is undefined) (注意:您可以将其他插槽连接到按钮的clicked信号,但是它们被调用的顺序是不确定的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM