自动完成在 focusIn 上弹出,但无法在 QLineEdit 中从选择中设置文本


from PyQt4.Qt import Qt, QObject,QLineEdit
from PyQt4 import QtGui, QtCore
import utils
class DirLineEdit(QLineEdit, QtCore.QObject):
    """docstring for DirLineEdit"""
    def __init__(self):
        super(DirLineEdit, self).__init__()
        self.xmlDataObj = utils.ReadWriteCustomPathsToDisk()
        self.defaultList = self.xmlDataObj.xmlData().values()
        self._pathsList()
    def focusInEvent(self, event):
        self.completer().complete()
    def _pathsList(self):        
        completerList = QtCore.QStringList()
        for i in self.defaultList:
            completerList.append(QtCore.QString(i))
        lineEditCompleter = QtGui.QCompleter(completerList)
        self.setCompleter(lineEditCompleter)
    def __dirCompleter(self):
        dirModel = QtGui.QFileSystemModel() 
        dirModel.setRootPath(QtCore.QDir.currentPath()) 
        dirModel.setFilter(QtCore.QDir.AllDirs | QtCore.QDir.NoDotAndDotDot | QtCore.QDir.Files) 
        dirModel.setNameFilterDisables(0) 
        completer = QtGui.QCompleter(dirModel, self)    
        completer.setModel(dirModel)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) 
        self.setCompleter(completer)
app = QtGui.QApplication(sys.argv)
smObj = DirLineEdit()
smObj.show()
app.exec_()

上面的代码有效,除了我无法从我在自动完成中选择的文本中设置文本,该选择在事件中弹出焦点..知道为什么我无法制作完成器选择的设置文本吗?

问题是你对focusInEvent的重新实现没有调用它的基类方法。除非您确定要完全覆盖默认行为,否则应始终执行此操作。在这种特殊情况下,在调用完成器之前调用基类focusInEvent方法也很重要,因为这显然会重新获得焦点。

下面是一个修复示例代码中问题的工作演示:

from PyQt4 import QtGui, QtCore
class LineEdit(QtGui.QLineEdit):
    def __init__(self, strings, parent):
        QtGui.QLineEdit.__init__(self, parent)
        self.setCompleter(QtGui.QCompleter(strings, self))
    def focusInEvent(self, event):
        QtGui.QLineEdit.focusInEvent(self, event)
        self.completer().complete()
class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        strings = 'one two three four five six seven eight'.split()
        self.edit1 = LineEdit(strings, self)
        self.edit2 = LineEdit(strings, self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit1)
        layout.addWidget(self.edit2)
if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

相关内容

  • 没有找到相关文章

最新更新