我有一个数据列表,显示在Qcombobox中(使用' addItems') 现在 - 如果通过使用按钮从文件加载数据来更改列表 - 我不会在组合框中看到新数据。 新数据在那里(我可以在加载后打印) 我错过了什么? 下面是简化gui的代码
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QFileDialog
import pandas as pd
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def __init__(self):
self.comboData=['None']
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(456, 172)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.comboBox = QtGui.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(120, 60, 69, 22))
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.comboBox.setEditable(True)
self.comboBox.addItems(self.comboData)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(260, 60, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(self.load)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 456, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "Load", None))
def load(self):
fileName=QFileDialog.getOpenFileName(MainWindow,'Load File')
data_pd=pd.read_csv(fileName,index_col=0,na_filter=False)
self.comboData=list(data_pd.var1)
print(self.comboData)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
答案 0 :(得分:6)
您只需将数据加载到self.comboData
,但不要将其加载到self.comboBox
。
def load(self):
添加以下行:
self.comboBox.clear() # delete all items from comboBox
self.comboBox.addItems(self.comboData) # add the actual content of self.comboData
由于QComboBox
使用的模型在项目中的数据发生更改时会发出dataChanged()
信号,因此组合框会自动重新绘制,无需通过
self.comboBox.update()