你好我在python和pyqt4编写一个程序来控制放大器。程序连接一个串口(pyserial模块)。现在我想修改我的版本,它可以在其他平台和计算机上使用。我已经加载并添加了一个包含所有串口的列表到ComboBox。因为每次启动程序时都要选择并连接端口,我希望ComboBox保存最后选择的端口并连接到它。我是Python的新手,不知道。如何保存和加载ComboBox中选择的最后一个String?
答案 0 :(得分:0)
我能想到的只是做一些文件I / O.
说,你有一个文件index.txt。您需要存储索引,因此,每次激活组合框时,您以读取模式打开文件,读取内部数字,关闭文件,将整数更改为当前项目的索引,打开文件处于写入模式,将新整数写入其中并再次关闭文件。这样,您始终将最新选择的项目索引存储在文件中。
然后,在启动时,再次打开文件并读取里面的字符串。您可以使用.setCurrentIndex()将组合框的当前索引设置为此字符串的索引。这将自动连接到组合框的currentIndexChanged()信号。
这是一个示例程序:
import sys
from PyQt4 import QtGui, QtCore
class Main(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.initUI()
def initUI(self):
centralwidget = QtGui.QWidget()
self.combo = QtGui.QComboBox(self)
self.combo.addItem("Serial 1")
self.combo.addItem("Serial 2")
self.combo.addItem("Serial 3")
self.combo.addItem("Serial 4")
self.combo.addItem("Serial 5")
self.combo.currentIndexChanged[str].connect(self.Show)
f = open("index.txt","rt")
index = f.read()
f.close()
self.combo.setCurrentIndex(int(index))
grid = QtGui.QGridLayout()
grid.addWidget(self.combo,0,0)
centralwidget.setLayout(grid)
self.setGeometry(300,300,280,170)
self.setCentralWidget(centralwidget)
def Show(self, item):
print("Connected to: ",item)
f = open("index.txt","rt")
index = f.read()
f.close()
index = self.combo.currentIndex()
f = open("index.txt","wt")
f.write(str(index))
f.close()
def main():
app = QtGui.QApplication(sys.argv)
main= Main()
main.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
注意:为此,您需要创建一个index.txt文件,其中包含一个数字,与您的程序位于同一目录中。