且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将小部件添加到 qtablewidget pyqt

更新时间:2023-11-14 17:07:58

您将几个问题合并为一个...简而言之,是的,您可以向 QTableWidget 添加按钮 - 您可以向 QTableWidget 添加任何小部件通过调用 setCellWidget 的表格小部件:

You have a couple of questions rolled into one...short answer, yes, you can add a button to a QTableWidget - you can add any widget to the table widget by calling setCellWidget:

# initialize a table somehow
table = QTableWidget(parent)
table.setRowCount(1)
table.setColumnCount(1)

# create an cell widget
btn = QPushButton(table)
btn.setText('12/1/12')
table.setCellWidget(0, 0, btn)

但这听起来不像你真正想要的.

But that doesn't sound like what you actually want.

听起来您想要对用户双击您的一个单元格做出反应,就好像他们单击了一个按钮,大概是为了调出对话框或编辑器或其他东西.

It sounds like you want to react to a user double-clicking one of your cells, as though they clicked a button, presumably to bring up a dialog or editor or something.

如果是这样,您真正需要做的就是从 QTableWidget 连接到 itemDoubleClicked 信号,如下所示:

If that is the case, all you really need to do is connect to the itemDoubleClicked signal from the QTableWidget, like so:

def editItem(item):
    print 'editing', item.text()    

# initialize a table widget somehow
table = QTableWidget(parent)
table.setRowCount(1)
table.setColumnCount(1)

# create an item
item = QTableWidgetItem('12/1/12')
table.setItem(0, 0, item)

# if you don't want to allow in-table editing, either disable the table like:
table.setEditTriggers( QTableWidget.NoEditTriggers )

# or specifically for this item
item.setFlags( item.flags() ^ Qt.ItemIsEditable)

# create a connection to the double click event
table.itemDoubleClicked.connect(editItem)