'Limit the text input of editable QComboBox
I want to limit the possibility of text-input to the text of the combobox items.
from PyQt5.QtWidgets import QApplication, QComboBox
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
combo = QComboBox()
combo.setEditable(True)
combo.insertItems(0, ['Bob', 'Anne', 'Tim'])
combo.show()
sys.exit(app.exec_())
In the combobox above, I will not be able to type in e.g. 'Peter' or any other string that is unlike Bob, Anne or Tim.
EDIT:
I have already tried this code, but I failed and I don't know if I am on the right way:
from PyQt5.QtGui import QValidator
from PyQt5.QtWidgets import QApplication, QComboBox
class Validator(QValidator):
names = ['Bob', 'Anne', 'Tim']
def validate(self, _text, _pos):
for name in self.names:
if _text == name[0:_pos]:
print(f"match")
return QValidator.Acceptable
return QValidator.Intermediate
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
combo = QComboBox()
combo.setEditable(True)
combo.insertItems(0, ['Bob', 'Anne', 'Tim'])
c_validator = Validator(combo.lineEdit())
combo.setValidator(c_validator)
combo.show()
sys.exit(app.exec_())
This code runs into the error: 'TypeError: invalid result from Validator.validate()'
Additional explanation:
In the picture below you can see a combobox where you can enter a font style.

I have inputed here the three letters a, r and i. After pressing the return- or the tabulator-key the item 'Arial' is selected:
But in this combobox I can also input 'nonsens'. It does nothing! But to prevent an (inexperienced) user to input wrong stuff, I would like this behaviour.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

