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

上面的代码有效,除了我无法设置我在自动完成中所做的选择中的文本,它会在事件中弹出焦点。知道为什么我无法设置完成者选择的文本吗?

4

1 回答 1

0

问题是您的重新实现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_())
于 2013-11-01T23:58:58.003 回答