[英]pyqt5 "QTableWidget" and "setItem" issue
我想使用 QTableWidgetItem 但出了點問題..我認為算法如下。
push bottom("apply") -> 更改 Table 小部件項目(但沒有任何變化......)
這里是我的python代碼...請注意評論。
# -*- coding: utf-8 -*-
[..import..]
class UserModel(QStandardItemModel):
[..item modeling for combobox..]
class Tab_1(QWidget):
def __init__(self, API, parent=None):
super(Tab_1, self).__init__(parent=parent)
self.API = API
self.ipaddr = []
self.init_widget()
def init_widget(self):
[..GropBox & Layout define..]
#### ComboBox define
manufacturer = ["a", "b", "c"]
combo_model = UserModel(manufacturer)
combobox = QComboBox()
combobox.setModel(combo_model)
combobox.currentTextChanged.connect(self.select_manufacturer)
[..pushbotton define..]
pushbottom_list[1].released.connect(self.apply) ## connect Slot
[..combo box event..]
#### Push bottom Event
def apply(self): ## apply button slot
main = main1()
print("apply")
item = ["a", "b", "c", "d", "1", "2"]
main.table_add_item(item) ## call
class main1(QMainWindow):
def __init__(self):
super(QMainWindow, self).__init__()
self.initUI()
def initUI(self):
[..menuBar define..]
self.table = QTableWidget(self)
self.table.setGeometry(0, 21, 300, 700)
self.table.setRowCount(200)
self.table.setColumnCount(1)
self.tbw = QTabWidget(self)
self.tbw.setGeometry(300,21,400,500)
self.tbw.addTab(Tab_1("API"), "Search API")
[..layout define..]
def status_msg(self, msg):
self.sb.showMessage(msg)
def table_add_item(self, item): ## setItem...
for i in range(len(item)):
print(item[i]) ## work
self.table.setItem(i, 0, QTableWidgetItem(item[i])) ## Not Working!!! and nothing changed......
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = main1()
ex.show()
sys.exit(app.exec_())
問題很簡單,說明你忘記了OOP的基本概念:類是對一組元素的行為的抽象,即每次使用類創建一個對象時,該對象與之前的不同一(除了行為被修改)。
在您的情況下,類 main1 的 ex 對象:
ex = main1()
不同於:
main = main1()
在前面的命令中,您正在創建一個新窗口,該窗口有自己的 QTableWidget,您將這些值添加到該 QTableWidget。
你會說:如果我正在創建一個窗口,為什么它不顯示? ,首先是因為你沒有調用show,其次是因為它是一個局部變量,當它執行完apply時就被淘汰了。
解決方法很簡單,獲取原來的main1,為此有幾種方法:
使用parent()
方法:
def apply(self): ## apply button slot print("apply") main =self.parent().parent().parent() items = ["a", "b", "c", "d", "1", "2"] main.table_add_item(items) ## call
使用topLevelWidgets()
方法:
def apply(self): ## apply button slot main = [w for w in QApplication.topLevelWidgets() if isinstance(w, main1)][0] items = ["a", "b", "c", "d", "1", "2"] main.table_add_item(items) ## call
另一種替代方法是將該對象顯式傳遞給類 Tab_1 的構造函數。
最后,可以使 table_add_item 方法更具可讀性
def table_add_item(self, items):
for i, text in enumerate(items):
self.table.setItem(i, 0, QTableWidgetItem(text))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.