向QTableWidget添加小部件(PyQt)

15

有没有办法在QTableWidget中添加类似按钮的功能?但是单元格中的日期仍然必须显示,例如如果用户双击单元格,我能否发送像按钮一样的信号?谢谢!

edititem():

def editItem(self,clicked):
    if clicked.row() == 0:
        #go to tab1
    if clicked.row() == 1:
        #go to tab1
    if clicked.row() == 2:
        #go to tab1
    if clicked.row() == 3:
        #go to tab1

表触发器:

self.table1.itemDoubleClicked.connect(self.editItem)
2个回答

33

您的问题有几个方面...简短来说,是的,您可以在QTableWidget中添加按钮 - 只需调用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)

但这似乎不是您实际想要的。

听起来您希望对用户双击单元格做出反应,就像他们单击按钮一样,可能是为了打开对话框或编辑器等。

如果是这种情况,您只需要连接到 QTableWidget 的 itemDoubleClicked 信号即可,示例如下:

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)

如何使行在用户单击时突出显示而不是单个单元格。 - user1582983
4
执行:table.setSelectionBehavior(QTableWidget.SelectRows)。意思是设置表格的选择行为为选择整行。 - Eric Hulser
当然,你可以做任何你想做的事情。链接到itemClicked信号,然后在连接的slot中修改你的选项卡。除此之外,我需要更多的代码才能给出更好的答案。 - Eric Hulser
2
您将其设置在了错误的微件上 - QWidget 没有该属性。我假设如果您正在尝试设置选项卡,则某处应该有选项卡微件 - 那是您必须设置索引值的地方。http://qt-project.org/doc/qt-4.8/qtabwidget.html 无意冒犯,但我已经回答了您的问题,您现在需要一个新问题 - 如果您仍然在处理更多的代码示例而不是将此推入新主题中,我将发布该问题。 - Eric Hulser
@EricHulser 我使用了你的方法,并与for循环集成(它可以正常工作,用于从json文件加载所有数据)。但是按钮只添加到最后一行?我不知道问题出在哪里,因为数据的加载正常工作,这意味着for循环没有问题。你能帮忙吗? - Mehul
显示剩余6条评论

2
在PyQt4中向QTableWidget添加按钮:最初的回答
btn= QtGui.QPushButton('Hello')
qtable_name.setCellWidget(0,0, btn) # qtable_name is your qtablewidget name

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接