QComboBox在文本大小写不同的情况下替换编辑文本

1 投票
1 回答
2178 浏览
提问于 2025-04-16 05:40

我遇到了一个问题,QComboBox不让我把输入的文本改成已经存在的、但大小写不同的选项。

下面是示例代码。我想在一个已经包含'One'这个选项的下拉框中输入'one',但不希望文本被自动改成'One'。现在的情况是,当下拉框失去焦点时,文本会立刻变回'One'。

虽然关闭自动完成的大小写敏感功能可以解决这个问题,但这样做的副作用是它就不太好用了(比如输入'one'时不会显示补全选项)。

我还尝试重写QComboBox的focusOutEvent事件,来恢复正确的文本,但这样一来,复制粘贴就不管用了。更改补全器也没有帮助。

下拉框这样行为对我的应用程序有很大的影响。如果有人有好的建议(或者我漏掉了什么明显的东西),请告诉我。

我在Ubuntu 10.04上使用的是Qt 4.6.2和PyQt 4.7.2,但在其他版本的操作系统和Qt 4.5以上的版本中也遇到过这个问题。

谢谢,祝好。

示例代码:

from PyQt4.QtGui import * 
from PyQt4.QtCore import SIGNAL, Qt 

class Widget(QWidget): 
    def __init__(self, parent=None): 
        super(Widget, self).__init__(parent) 
        combo = QComboBox() 
        combo.setEditable(True) 
        combo.addItems(['One', 'Two', 'Three'])
        lineedit = QLineEdit() 

        layout = QVBoxLayout() 
        layout.addWidget(combo) 
        layout.addWidget(lineedit) 
        self.setLayout(layout) 

app = QApplication([]) 
widget = Widget() 
widget.show() 
app.exec_()

1 个回答

1
from PyQt4.QtGui import * 
from PyQt4.QtCore import SIGNAL, Qt, QEvent


class MyComboBox(QComboBox):
    def __init__(self):
        QComboBox.__init__(self)

    def event(self, event):
        if event.type() == QEvent.KeyPress and event.key() == Qt.Key_Return:
            self.addItem(self.currentText())

        return QComboBox.event(self, event)

class Widget(QWidget): 
    def __init__(self, parent=None): 
        super(Widget, self).__init__(parent) 
        combo = MyComboBox() 
        combo.setEditable(True) 
        combo.addItems(['One', 'Two', 'Three'])
        lineedit = QLineEdit() 

        layout = QVBoxLayout() 
        layout.addWidget(combo) 
        layout.addWidget(lineedit) 
        self.setLayout(layout) 

app = QApplication([]) 
widget = Widget() 
widget.show() 
app.exec_()

这个问题就是,它会允许你在下拉框里添加重复的选项。我试着在条件语句里加上自查的代码(self.findText(...)),但是即使用 Qt.MatchExactly | Qt.MatchCaseSensitive 也会把 "bla"、"bLa" 和 "BLA" 都当作相同的匹配项。我想你自己也会发现这个问题的。

撰写回答