2016-09-27 151 views
0

我真的试过一切来解决我的问题,但它不起作用。 这里是我简单的代码把Comboboxes放在表格的每一行中。它实际上适用于setItem(),我使用它将字符串放入每一行。但它不能和setCellWidget()一起使用,我必须使用它来将Combobox放入行中。这就好像setCellWdiget()将它放入行后删除了组合框,因为它最终只出现在最后一行,我不明白为什么。 如果你能帮我一个人,那会很棒。提前谢谢了!QTableWidget中的PyQt5 QComboBox

下面是代码:

import sys 
from PyQt5 import QtWidgets, QtCore 

class Window(QtWidgets.QMainWindow): 

    def __init__(self): 
     super(Window, self).__init__() 
     self.setGeometry(50,50,500,500) 
     self.setWindowTitle('PyQt Tuts') 
     self.table() 


    def table(self): 

     comboBox = QtWidgets.QComboBox() 

     self.tableWidget = QtWidgets.QTableWidget() 
     self.tableWidget.setGeometry(QtCore.QRect(220, 100, 411, 392)) 
     self.tableWidget.setColumnCount(2) 
     self.tableWidget.setRowCount(5) 
     self.tableWidget.show() 

     attr = ['one', 'two', 'three', 'four', 'five'] 
     i = 0 
     for j in attr: 
      self.tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(j)) 
      self.tableWidget.setCellWidget(i, 1, comboBox) 
      i += 1 


def run(): 
    app = QtWidgets.QApplication(sys.argv)  
    w = Window() 
    sys.exit(app.exec_())  

run() 

回答

1

您创建一个组合框,所以当你把它变成一个细胞,它是从prevoius细胞中移除。 您必须为每个单元创建一个组合框(在for循环中)。

例子:

attr = ['one', 'two', 'three', 'four', 'five'] 
i = 0 
for j in attr: 
    self.tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(j)) 
    comboBox = QtWidgets.QComboBox() 
    self.tableWidget.setCellWidget(i, 1, comboBox) 
    i += 1 
+0

你有你的意思的例子吗? – saitam

+0

添加示例 – Fabio

+0

+1根据文档:'设置给定小部件显示在给定行和列的单元格中,将小部件的所有权传递给表。 – Frodon