pyqt5 autocomplete QLineEdit - Google places autocomplete

不想你离开。 提交于 2019-12-04 02:06:23

问题


I am trying to create something like this (autocomplete places) in pyqt5 QLineEdit.

There is a class called QCompleter with which i can suggest the content, but it requires an already formed list, but this google places api is a suggestion based function, how can i send each keystroke to google api and get the suggestion back and load in Qtextedit, is there a better way to do it


回答1:


For this case you can create a custom model that makes a request using Place Autocomplete, and set that model to a QCompleter:

import json
from PyQt5 import QtCore, QtGui, QtWidgets, QtNetwork

API_KEY = "<API_KEY>"

class SuggestionPlaceModel(QtGui.QStandardItemModel):
    finished = QtCore.pyqtSignal()
    error = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(SuggestionPlaceModel, self).__init__(parent)
        self._manager = QtNetwork.QNetworkAccessManager(self)
        self._reply = None

    @QtCore.pyqtSlot(str)
    def search(self, text):
        self.clear()
        if self._reply is not None:
            self._reply.abort()
        if text:
            r = self.create_request(text)
            self._reply = self._manager.get(r)
            self._reply.finished.connect(self.on_finished)
        loop = QtCore.QEventLoop()
        self.finished.connect(loop.quit)
        loop.exec_()

    def create_request(self, text):
        url = QtCore.QUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json")
        query = QtCore.QUrlQuery()
        query.addQueryItem("key", API_KEY)
        query.addQueryItem("input", text)
        query.addQueryItem("types", "geocode")
        query.addQueryItem("language", "en")
        url.setQuery(query)
        request = QtNetwork.QNetworkRequest(url)
        return request

    @QtCore.pyqtSlot()
    def on_finished(self):
        reply = self.sender()
        if reply.error() == QtNetwork.QNetworkReply.NoError:
            data = json.loads(reply.readAll().data())
            if data['status'] == 'OK':
                for prediction in data['predictions']:
                    self.appendRow(QtGui.QStandardItem(prediction['description']))
            self.error.emit(data['status'])
        self.finished.emit()
        reply.deleteLater()
        self._reply = None

class Completer(QtWidgets.QCompleter):
    def splitPath(self, path):
        self.model().search(path)
        return super(Completer, self).splitPath(path)

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self._model = SuggestionPlaceModel(self)
        completer = Completer(self, caseSensitivity=QtCore.Qt.CaseInsensitive)
        completer.setModel(self._model)
        lineedit = QtWidgets.QLineEdit()
        lineedit.setCompleter(completer)
        label = QtWidgets.QLabel()
        self._model.error.connect(label.setText)
        lay = QtWidgets.QFormLayout(self)
        lay.addRow("Location: ", lineedit)
        lay.addRow("Error: ", label)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(400, w.sizeHint().height())
    w.show()
    sys.exit(app.exec_())



来源:https://stackoverflow.com/questions/55027186/pyqt5-autocomplete-qlineedit-google-places-autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!