如何在QComboBox中标记当前项目文本?

how to mark current item text in QComboBox?

我将组合框用作具有历史记录的简单命令行。

信号槽定义如下:

QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Return),
                    self.comboBox_cmd,
                    activated=self.queryLine)

...和广告位:

@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)

这真的很好用。现在,如何在按 Enter 后标记当前项目的整个文本,以便我可以根据需要替换整行?

您可以自动 select 通过捕捉 return/enter 按键来编辑行的文本:

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()

好的,我已经全部组装好了 :) 问题是,我以前需要定义一个快捷方式,因为 QComboBox 没有 returnPressed 属性。 使用自定义小部件,我当然可以轻松更改它:

class SelectCombo(QtWidgets.QComboBox):
'''

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!")

在我的 GUI 应用程序中,我只需要以下信号槽定义即可使其工作:

    ## 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)

非常感谢您的帮助!