I'm very new to QML and somewhat confused on how to properly connect more than one element across python and QML (I'm using python 2.7!). I have python script to print weather data, and a QML application that is supposed to take in the input as "cityname."
The user theoretically types a city into the textfield, hits the button, and python takes the input, finds the weather data, and prints it to the QML window. I'm struggling with how the connections with textfield+button+pythonfunction will work! The python function without QML works and the QML produces a window with a textinput and a button.
Here's my code:
QML (weather5.qml)
import QtQuick 2.0
import QtQuick.Controls 2.1
import QtQuick.Window 2.2
ApplicationWindow {
title: qsTr("Test")
width: 300
height: 450
visible: true
Column {
spacing: 20
TextField {
placeholderText: qsTr("City")
echoMode: TextInput.City
id: city
selectByMouse: true
}
ListView{
model: cityy
id: hi
delegate: Text { text: city.display }
}
Button {
signal messageRequired
objectName: "myButton"
text: "Search"
onClicked: {
print(hi)
}
}
}
Connections {
target:
}
}
and here's the python!! (pyweather.py)
import requests, json, os
from PyQt5.QtQml import QQmlApplicationEngine, QQmlEngine, QQmlComponent, qmlRegisterType
from PyQt5.QtCore import QUrl, QObject, QCoreApplication, pyqtProperty, QStringListModel, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QGuiApplication
import sys
class City(QObject):
def __init__(self):
QObject.__init__(self)
enterCity = pyqtSignal(str, arguments=["weat"])
@pyqtSlot(str)
def weat(self, city_name):
api_key = "key" #I've excluded my key for this post
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = "http://api.openweathermap.org/data/2.5/weather?q=" + city_name + api_key
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
res = requests.get(complete_url)
data = res.json()
temp = data['main']['temp']
description = data['weather'][0]['description']
print('Temperature : {} degree Kelvin'.format(temp))
rett = ['Temperature : ' + str(temp) + " degree Kelvin"]
return rett
self.enterCity.emit(rett)
else:
print(" City Not Found ")
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
city = City()
engine.rootContext().setContextProperty("cityy", city)
engine.load(QUrl.fromLocalFile('weather5.qml'))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())