问题
I'm using a combo box as a simple command line with a history.
Here's the signal-slot definition:
QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return),
self.comboBox_cmd,
activated=self.queryLine)
...and the slot:
@QtCore.pyqtSlot()
def queryLine(self):
'''
Read cmd string from widget and write to device.
'''
## comboBox can be enhanced with a history
cmd = self.comboBox_cmd.currentText()
cmds = [self.comboBox_cmd.itemText(i) for i in range(self.comboBox_cmd.count())]
if not cmds or cmds[-1] != cmd:
self.comboBox_cmd.addItem(cmd)
self.query(cmd)
This works really well. Now, how can I mark the entire text of the current item after pressing Enter, so that I can replace the whole line if I so wish?
回答1:
You can automatically select the text of the line edit by catching the return/enter key press:
class SelectCombo(QtWidgets.QComboBox):
def keyPressEvent(self, event):
# call the base class implementation
super().keyPressEvent(event)
# if return/enter is pressed, select the text afterwards
if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
self.lineEdit().selectAll()
回答2:
Ok, I've got it all assembled :) Problem was, I previously needed to define a shortcut since QComboBox does not have a returnPressed attribute. With the custom widget, I can change that easily, of course:
class SelectCombo(QtWidgets.QComboBox):
'''
https://stackoverflow.com/questions/62594748/how-to-mark-current-item-text-in-qcombobox/62598381
Modified QComboBox which selects the current text after Enter/Return.
'''
returnPressed = QtCore.pyqtSignal(str)
def keyPressEvent(self, event):
## call the base class implementation
super().keyPressEvent(event)
## if return/enter is pressed, select the text afterwards
if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
self.lineEdit().selectAll()
self.returnPressed.emit("Enter pressed!")
And in my GUI app, I simply need the following signal-slot definition to make it work:
## 1) QLineEdit has "returnPressed" but no history
#self.lineEdit_cmd.returnPressed.connect(self.queryLine)
## 2) QComboBox has history, but no "returnPressed" attritbute==> need to define a shortcut
#QtCore.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return),
#QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return),
# self.comboBox_cmd,
# activated=self.queryLine)
## 3) custom SelectCombo widget has QComboBox's history plus "returnPressed"
self.comboBox_cmd.returnPressed.connect(self.queryLine)
Thanks a lot for helping me!
来源:https://stackoverflow.com/questions/62594748/how-to-mark-current-item-text-in-qcombobox