2016-09-27 150 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