Как с помощью QComboBox добавить данные в модель (базу данных)
В QComboBox данные поступают из модели (реализация QAbstractListModel). QComboBox.setEditable(True) Хочу, чтобы когда вводишь данные в Комбобокс по нажатию Enter новые данные добавлялись в модель. Сейчас у меня по сигналу returnPressed после ввода данных currentText() пустой. Соответственно и в модель добавляется пустая строка. Другими словами, как мне сохранить текст перед нажатием Enter?
import sys
from PyQt5.QtWidgets import QWidget, QComboBox,QLabel, QHBoxLayout, QApplication
from PyQt5.QtCore import Qt
from myListModel import MyListModel,MyListListModel
mylist=[1,2,3,4]
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUi()
def initUi(self):
self.cBox=QComboBox()
model=MyListListModel(mylist)
self.cBox.setModel(model)
self.label=QLabel()
self.cBox.setEditable(True)
lineedit=self.cBox.lineEdit()
lineedit.returnPressed.connect(self.addText)
hbox=QHBoxLayout()
hbox.addWidget(self.cBox)
hbox.addWidget(self.label)
self.setLayout(hbox)
self.setGeometry(300,300,300,150)
self.show()
def addText(self):
if self.cBox.currentIndex()<0:
self.cBox.model().setData(self.cBox.currentText())
if __name__=='__main__':
app=QApplication(sys.argv)
ex=Example()
sys.exit(app.exec_())
Ответы (1 шт):
Пока реализовал такой костыль. Над QComboBox накладывается QLineEdit. Соответственно, по сигналу currentIndexChanged меняется текст в QLineEdit Для QLineEdit устанавливается QСompleter от нашей же модели. Это нужно для того, что при вводе текста нам выдавался уже имеющийся в модели текст. Если текст новый, то при нажатии Enter, проверяется на то что текста нет в модели и вызывается setData модели. Еще надо реализовать, чтобы индекс QComboBox устанавливался в соответствии с введенным в QLineEdit текстом.
import sys
from PyQt5.QtWidgets import QWidget, QComboBox,QLabel, QHBoxLayout, QApplication
from PyQt5.QtCore import Qt
from myListModel import MyListListModel
mylist=[1,2,3,4]
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUi()
def initUi(self):
self.cBox=QComboBox(self)
self.cBox.setGeometry(200,80,300,20)
model=MyListListModel(mylist)
self.cBox.setModel(model)
self.lineEdit=QLineEdit(self)
self.lineEdit.setGeometry(200,80,280,20)
self.lineEdit.setText(self.cBox.currentText())
completer=QCompleter(model)
self.lineEdit.setCompleter(completer)
self.cBox.currentIndexChanged.connect(self.indexChanged)
self.lineEdit.returnPressed.connect(self.addText)
self.setGeometry(300,300,300,150)
self.show()
def indexChanged(self):
self.lineEdit.setText(self.cBox.currentText())
def addText(self):
text=int(self.lineEdit.text())
if text not in self.cBox.model().results:
self.cBox.model().setData(text)