选择QCompleter项后,无法清除QLineEdit

时间:2018-02-28 12:13:51

标签: python pyqt4 qlineedit qcompleter

从QCompleter中选择项目后,从QLineEdit清除文本时出现问题。我想打印从QCompleter中选择的项目的文本,然后立即清除QLineEdit,我只是成功打印了文本,但我无法在之后清除QLineEdit文本。

这是我的代码:

import sys
from PyQt4 import QtGui, QtCore

auto_completer_words = ["chair"]


def get_data(model):
    model.setStringList(auto_completer_words)


class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.resize(300, 300)

        self.line_edit = QtGui.QLineEdit(self)
        self.line_edit.setGeometry(QtCore.QRect(100, 100, 100, 30))

        self.completer = QtGui.QCompleter()
        self.line_edit.setCompleter(self.completer)

        model = QtGui.QStringListModel()
        self.completer.setModel(model)
        get_data(model)

        self.completer.activated.connect(self.get_data_in_le)


def get_data_in_le(self):
    print(self.line_edit.text())
    self.line_edit.clear()


def main():
    app = QtGui.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:2)

问题是在分配值之前触发了激活的QCompleter信号,以便在结束时clear()起作用,但在空QLineEdit时清除QTimer。解决方案是稍后清理,因为它可以使用def get_data_in_le(self): print(self.line_edit.text()) QtCore.QTimer.singleShot(0, self.line_edit.clear)

import {AppComponent} from './app.component';
import {Injectable, Input} from '@angular/core';
import { Router, CanActivate } from '@angular/router';

@Injectable()
export class AuthGuardService implements CanActivate {
    @Input() appc: AppComponent;                         
    canActivate(): boolean {
        if(!online) {                                    //if status isn't online
            this.router.navigate(['loginEmail']);        //go to loginpage
            this.appc.changeHeaderEnable(false);         //change value
            return false;
        }
        this.appc.changeHeaderEnable(true);
        return true;
    }
}

答案 1 :(得分:1)

更好的解决方案是:

self.connect(self.completer, QtCore.SIGNAL("activated(const QString&)"), self.line_edit.clear, QtCore.Qt.QueuedConnection)