Issue
The code below creates QComboBox and QPushButton both assigned to the same layout. Combobox is set to be editable so the user is able to type a new combobox item's value. If the user hits Tab keyboard key (instead of Enter) the New Value will not be added to the ComboBox. Question: How to make sure the ComboBox's items are updated with the New Value even if the user leaves the ComboBox with Tab key?
from PyQt4 import QtGui
def comboActivated(arg=None):
print '\n ...comboActivated: %s'%arg
widget = QtGui.QWidget()
layout = QtGui.QVBoxLayout()
widget.setLayout(layout)
combo = QtGui.QComboBox()
combo.setEditable(True)
combo.addItems(['One','Two','Three'])
combo.activated.connect(comboActivated)
layout.addWidget(combo)
layout.addWidget(QtGui.QPushButton('Push'))
widget.show()
Solution
When a user edits the text in the box, the editTextChanged()
signal is emitted with the edited text as its argument. In addition, when the widget itself loses focus, as when the user types Tab
to move to the button, the widget emits the focusOutEvent()
signal. The argument for this signal is a QFocusEvent
, which you can query for the reason focus was lost. The reason()
method of the event would return Qt.TabFocusReason
, for example, if the user hit the Tab
button to leave the widget.
You can connect a slot to either (or both) of these signals, so that when the user leaves the widget after editing text, you process it and add it to the box's list of values.
You may also want to look into the QValidator
class and its subclasses, which you attach to widgets with editable text, and define the types of valid input for the widget (e.g., integers, text, etc.). This is the best and easiest way to verify a user's input for editable widgets.
Answered By - bnaecker
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.