I am using PySide2, Qt Quick, and Qt Creator.
I am trying to make it so that it uses a variable from the text field that is stored in the QML file and run a command that prints the variable into the console using print().
In the main.py file, I created this code that finds the price of assets of cryptocurrencies.
def assetSet(self):
asset = "xrp"
url2 = f'https://coinmarketcap.com/currencies/{asset}'
page2 = requests.get(url2)
soup2 = bs(page2.text, 'html.parser')
price2 = soup2.find(class_="priceValue___11gHJ")
price12 = str(price2)
result2 = re.search('<div class="priceValue___11gHJ">(.*)</div>', price12)
result12 = result2.group(1)
self.setAsset.emit(f"The price of {asset} is {result12}")
In the QML File, I have
CustomButton{
id: btnBdo
text: "Check"
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenterOffset: 200
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenterOffset: 0
font.pointSize: 20
colorMouseOver: "#21252d"
colorPressed: "#191d23"
colorDefault: "#2a303a"
onClicked: {
backend.assetSet()
}
}
CustomTextField {
id: textField
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenterOffset: -100
anchors.horizontalCenter: parent.horizontalCenter
font.pointSize: 20
placeholderText: qsTr("Enter a name")
objectName: "assetField"
}
I want the asset variable to equal the text field that is stored in the QML file and run this command when the button is clicked.
Is there a way to do this?
In this case it is best to use a slot that receives the data, and since the execution of the function is also synchronous then the signal is not necessary:
#Slot(str, result=str)
def assetSet(self, asset):
url2 = f'https://coinmarketcap.com/currencies/{asset}'
page2 = requests.get(url2)
soup2 = bs(page2.text, 'html.parser')
price2 = soup2.find(class_="priceValue___11gHJ")
price12 = str(price2)
result2 = re.search('<div class="priceValue___11gHJ">(.*)</div>', price12)
result12 = result2.group(1)
return f"The price of {asset} is {result12}"
onClicked: function(){
var resp = backend.assetSet(textField.text)
console.log(resp)
}
On the other hand, the request can block the Qt event loop causing the GUI to freeze so it is better to execute that task in another thread:
from functools import cached_property
import os.path
import re
import sys
import threading
import requests
from bs4 import BeautifulSoup as bs
from PySide2.QtCore import QObject, Qt, QUrl, Signal, Slot
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
class Worker(QObject):
finished = Signal(str)
def start(self, asset):
threading.Thread(target=self._execute, args=(asset,), daemon=True).start()
def _execute(self, asset):
url2 = f"https://coinmarketcap.com/currencies/{asset}"
page2 = requests.get(url2)
soup2 = bs(page2.text, "html.parser")
price2 = soup2.find(class_="priceValue___11gHJ")
price12 = str(price2)
result2 = re.search('<div class="priceValue___11gHJ">(.*)</div>', price12)
if result2 is not None:
result12 = result2.group(1)
self.finished.emit(f"The price of {asset} is {result12}")
return
self.finished.emit(f"failed for {asset}")
class Backend(QObject):
assetChanged = Signal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.worker.finished.connect(self.assetChanged)
#cached_property
def worker(self):
return Worker()
#Slot(str)
def assetSet(self, asset):
self.worker.start(asset)
def main():
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
backend = Backend()
engine.rootContext().setContextProperty("backend", backend)
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
file = os.path.join(CURRENT_DIR, "main.qml")
url = QUrl.fromLocalFile(file)
def handle_object_created(obj, obj_url):
if obj is None and url == obj_url:
QCoreApplication.exit(-1)
engine.objectCreated.connect(handle_object_created, Qt.QueuedConnection)
engine.load(url)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
width: 640
height: 480
visible: true
Column {
Button {
id: button
text: "Press me"
onClicked: function() {
backend.assetSet(textField.text);
}
}
TextField {
id: textField
placeholderText: qsTr("Enter a name")
}
Label {
id: label
}
}
Connections {
function onAssetChanged(asset) {
label.text = asset;
}
target: backend
}
}
Related
I made a QtQuick Window Gui Application for Python 3.8 on Windows. The last thing I cant figure out is how to display Python print() in the Gui Text Area. What i want is, that wherever in my Python code a print statement is and gets executed during runtime, i want to output it into the TextArea in my Gui app
I read the following post, but failed to implemet it, different errors occured and am more confused then before:
the closest and most usefull was this one:
How to capture output of Python's interpreter and show in a Text widget?
and some others:
Python/PyQt/Qt Threading: How do I print stdout/stderr right away?
How to Redirect a Python Console output to a QTextBox
How can I flush the output of the print function?
How do I direct console output to a pyqt5 plainTextEdit widget with Python?
Python Printing StdOut As It Received
working Sample Code to send a string from Python into QML TextArea
main.py
import os
from pathlib import Path
import sys
from vantage import daily
# load GUI libs
from PySide2.QtGui import QGuiApplication
from PySide2.QtCore import QSettings, QObject, Signal, Slot
from PySide2.QtQml import QQmlApplicationEngine
# load app
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load(os.fspath(Path(__file__).resolve().parent / "main.qml"))
class Backend(QObject):
textwritten = Signal(str, arguments=['writen'])
def __init__(self):
super().__init__()
self.timer = QTimer()
self.timer.setInterval(100)
self.timer.timeout.connect(self.writer)
self.timer.start()
# console output write function
def writer(self):
towrite = 'i am writing'
self.textwritten.emit(str(towrite))
# create an instance of the Python object (Backend class)
back_end = Backend()
# give data back to QML
engine.rootObjects()[0].setProperty('writen', back_end)
# close app
sys.exit(app.exec_())
main.qml
import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.15
Window {
width: 640
height: 480
visible: true
color: "#2f2f2f"
title: qsTr("alpha")
/*print out console text*/
property string texted: "Console Text"
property QtObject writen
ScrollView {
id: scrollViewCon
x: 58
y: 306
width: 507
height: 100
ScrollBar.vertical.verticalPadding: 4
ScrollBar.vertical.minimumSize: 0.4
ScrollBar.vertical.contentItem: Rectangle {
implicitWidth: 6
implicitHeight: 100
radius: width / 2
color: control.pressed ? "#81e889" : "#f9930b"
}
TextArea {
font.family: control.font
font.pointSize: 8
color:"#f9930b"
wrapMode: TextEdit.Wrap
KeyNavigation.priority: KeyNavigation.BeforeItem
KeyNavigation.tab: textField
placeholderTextColor : "#f9930b"
opacity: 1
text: texted
placeholderText: texted //qsTr("Console")
readOnly: true
background: Rectangle {
radius: 12
border.width: 2
border.color: "#f9930b"
}
}
}
Connections {
target: writen
function onTextwritten(msg) {
texted = msg;
}
}
}
i think what needs to happen is that everytime sys.stdout is called by print() it emits a signal with itself?
leaving main.qml as is and only changing main.py
main.py
...
class Backend(QObject):
textwritten = Signal(str, arguments=['writen'])
def __init__(self):
super().__init__()
sys.stdout = self.writer(str(sys.stdout))
def writer(self, message):
#towrite = 'i am writing'
self.textwritten.emit(message)
...
The print function writes over sys.stdout so the solution is to assign some QObject that has a write method that emits a signal. For this you can use contextlib.redirect_stdout:
import os
import sys
from contextlib import redirect_stdout
from functools import cached_property
from pathlib import Path
from PySide2.QtCore import (
QCoreApplication,
QDateTime,
QObject,
Qt,
QTimer,
QUrl,
Signal,
)
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
CURRENT_DIRECTORY = Path(__file__).resolve().parent
class RedirectHelper(QObject):
stream_changed = Signal(str, name="streamChanged", arguments=["stream"])
def write(self, message):
self.stream_changed.emit(message)
class TimerTest(QObject):
#cached_property
def timer(self):
return QTimer(interval=1000, timeout=self.handle_timeout)
def handle_timeout(self):
print(QDateTime.currentDateTime().toString())
def start(self):
self.timer.start()
def main():
ret = 0
redirect_helper = RedirectHelper()
with redirect_stdout(redirect_helper):
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty("redirectHelper", redirect_helper)
filename = os.fspath(CURRENT_DIRECTORY / "main.qml")
url = QUrl.fromLocalFile(filename)
def handle_object_created(obj, obj_url):
if obj is None and url == obj_url:
QCoreApplication.exit(-1)
engine.objectCreated.connect(handle_object_created, Qt.QueuedConnection)
engine.load(url)
timer_test = TimerTest()
timer_test.start()
ret = app.exec_()
sys.exit(ret)
if __name__ == "__main__":
main()
import QtQuick 2.12
import QtQuick.Controls 2.12
ApplicationWindow {
id: root
width: 640
height: 480
visible: true
Flickable {
id: flickable
flickableDirection: Flickable.VerticalFlick
anchors.fill: parent
TextArea.flickable: TextArea {
id: textArea
anchors.fill: parent
readOnly: true
font.pointSize: 8
color: "#f9930b"
wrapMode: TextEdit.Wrap
placeholderTextColor: "#f9930b"
opacity: 1
placeholderText: qsTr("Console")
background: Rectangle {
radius: 12
border.width: 2
border.color: "#f9930b"
}
}
ScrollBar.vertical: ScrollBar {
}
}
Connections {
function onStreamChanged(stream) {
textArea.insert(textArea.length, stream);
}
target: redirectHelper
}
}
I try to get the root object after window having completed, but I get a error:
QmlObj = self.engine.rootObjects()[0]
Error: list index out of range
The strange thing is that it works when I try to call foo.init_window() after the MouseArea having clicked.
Here is my python code:
main.py
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QObject, QUrl, Slot
import sys
import win32gui
flag = False
class Foo(QObject):
def __init__(self):
super().__init__()
self.engine = QQmlApplicationEngine()
#Slot()
def init_window(self):
global flag
if not flag:
QmlObj = self.engine.rootObjects()[0]
desk = win32gui.FindWindow("Progman", "Program Manager")
print(desk)
sndWnd = win32gui.FindWindowEx(desk, 0, "SHELLDLL_DefView", None)
print(sndWnd)
targetWnd = win32gui.FindWindowEx(sndWnd,
0, "SysListView32", "FolderView")
print(targetWnd)
win32gui.SetParent((int)(QmlObj.winId()), targetWnd)
flag = True
if __name__ == "__main__":
app = QApplication(sys.argv)
foo = Foo()
foo.engine.rootContext().setContextProperty("foo", foo)
foo.engine.load(QUrl("main.qml"))
# win = foo.engine.rootObjects()[0]
# win.show()
if not foo.engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
Here is the .qml file:
main.qml
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.0
Window {
width: 200
height: 100
visible: true
//flags: Qt.FramelessWindowHint
//flags: Qt.WindowStaysOnBottomHint
//flags: Qt.WindowMinMaxButtonsHint
Rectangle {
anchors.fill: parent
color: "red"
Component.onCompleted: foo.init_window()
MouseArea {
anchors.fill: parent
onClicked: foo.init_window()
}
Text {
anchors.centerIn: parent
text: "Hello, World!"
}
Button {
text: "Ok"
onClicked: {
console.log("OK Button clicked....")
}
}
}
}
The problem is that in Component.onCompleted the window(the rootObject) has finished building but the engine list has not been updated. The solution is to invoke init_window an instant later using Qt.callLater():
Component.onCompleted: Qt.callLater(foo.init_window)
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_())
The logic is to return the information through a signal or a property, in this case I will show how to return the information through a property.
As it has to update to some element of the QML then it has to notify then it must have associated to a signal. On the other hand, you should not use requests since it can block the eventloop (and freeze the GUI).
Considering the above, the solution is:
main.py
from functools import cached_property
import json
from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QUrl, QUrlQuery
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
import logging
logging.basicConfig(level=logging.DEBUG)
class WeatherWrapper(QObject):
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
dataChanged = pyqtSignal()
def __init__(self, api_key; str ="", parent: QObject = None) -> None:
super().__init__(parent)
self._data = dict()
self._has_error = False
self._api_key = api_key
#cached_property
def manager(self) -> QNetworkAccessManager:
return QNetworkAccessManager(self)
#property
def api_key(self):
return self._api_key
#api_key.setter
def api_key(self, key):
self._api_key = key
#pyqtProperty("QVariantMap", notify=dataChanged)
def data(self) -> dict:
return self._data
#pyqtSlot(result=bool)
def hasError(self):
return self._has_error
#pyqtSlot(str)
def update_by_city(self, city: str) -> None:
url = QUrl(WeatherWrapper.BASE_URL)
query = QUrlQuery()
query.addQueryItem("q", city)
query.addQueryItem("appid", self.api_key)
url.setQuery(query)
request = QNetworkRequest(url)
reply: QNetworkReply = self.manager.get(request)
reply.finished.connect(self._handle_reply)
def _handle_reply(self) -> None:
has_error = False
reply: QNetworkReply = self.sender()
if reply.error() == QNetworkReply.NoError:
data = reply.readAll().data()
logging.debug(f"data: {data}")
d = json.loads(data)
code = d["cod"]
if code != 404:
del d["cod"]
self._data = d
else:
self._data = dict()
has_error = True
logging.debug(f"error: {code}")
else:
self._data = dict()
has_error = True
logging.debug(f"error: {reply.errorString()}")
self._has_error = has_error
self.dataChanged.emit()
reply.deleteLater()
def main():
import os
import sys
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
app = QGuiApplication(sys.argv)
API_KEY = "API_HERE"
weather = WeatherWrapper()
weather.api_key = API_KEY
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty("weather", weather)
filename = os.path.join(CURRENT_DIR, "main.qml")
engine.load(QUrl.fromLocalFile(filename))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
ApplicationWindow {
title: qsTr("Weather App")
width: 300
height: 450
visible: true
ColumnLayout {
anchors.fill: parent
spacing: 20
TextField {
id: city_tf
placeholderText: qsTr("City")
Layout.alignment: Qt.AlignHCenter
font.pointSize:14
selectByMouse: true
}
Button {
text: "Search"
Layout.alignment: Qt.AlignHCenter
onClicked: {
weather.update_by_city(city_tf.text)
}
}
Label{
Layout.alignment: Qt.AlignHCenter
id: result_lbl
}
Item {
Layout.fillHeight: true
}
}
Connections {
target: weather
function onDataChanged(){
if(!weather.hasError()){
var temperature = weather.data['main']['temp']
result_lbl.text = "Temperature : " + temperature + " degree Kelvin"
}
}
}
}
Python2 syntax:
Note: Install cached_property(python2.7 -m pip install cached_property)
from cached_property import cached_property
import json
from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QUrl, QUrlQuery
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
import logging
logging.basicConfig(level=logging.DEBUG)
class WeatherWrapper(QObject):
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
dataChanged = pyqtSignal()
def __init__(self, api_key="", parent=None):
super(WeatherWrapper, self).__init__(parent)
self._data = {}
self._has_error = False
self._api_key = api_key
#cached_property
def manager(self):
return QNetworkAccessManager(self)
#property
def api_key(self):
return self._api_key
#api_key.setter
def api_key(self, key):
self._api_key = key
#pyqtProperty("QVariantMap", notify=dataChanged)
def data(self):
return self._data
#pyqtSlot(result=bool)
def hasError(self):
print(self._has_error)
return self._has_error
#pyqtSlot(str)
def update_by_city(self, city):
url = QUrl(WeatherWrapper.BASE_URL)
query = QUrlQuery()
query.addQueryItem("q", city)
query.addQueryItem("appid", self.api_key)
url.setQuery(query)
request = QNetworkRequest(url)
reply = self.manager.get(request)
reply.finished.connect(self._handle_reply)
def _handle_reply(self):
has_error = False
reply = self.sender()
if reply.error() == QNetworkReply.NoError:
data = reply.readAll().data()
logging.debug("data: {}".format(data))
d = json.loads(data)
code = d["cod"]
if code != 404:
del d["cod"]
self._data = d
else:
self._data = {}
has_error = True
logging.debug("error: {}".format(code))
else:
self._data = {}
has_error = True
logging.debug("error: {}".format(reply.errorString()))
self._has_error = has_error
self.dataChanged.emit()
reply.deleteLater()
def main():
import os
import sys
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
app = QGuiApplication(sys.argv)
API_KEY = "API_HERE"
weather = WeatherWrapper()
weather.api_key = API_KEY
engine = QQmlApplicationEngine()
engine.rootContext().setContextProperty("weather", weather)
filename = os.path.join(CURRENT_DIR, "main.qml")
engine.load(QUrl.fromLocalFile(filename))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I have to do a menu in QML that contains the list of items in a directory and, by clicking over one of them, it plays a video (player.play())
This is what I tried, but is not working
___.qml
Menu {
id: menu
contentItem: ListView {
model: ui.textMenu
}
}
Menu {
id: menu
y: -200
x: 100
Repeater{
model: ui.textMenu
MenuItem {
text: textMenu.entry
onClicked:{
player.source = textMenu.address
player.play()
}
} //x: model.x*(videoPlayer.width - 10)
}
}
___.py
self.__textMenu = QStandardItemModel(self)
menuRoles = {entryRole: b"entry", addressRole: b"address"}
self.__textMenu.setItemRoleNames(menuRoles)
def menu(self):
directoryPath = os.path.join(self.__currentPath, r"video" )
entries = os.listdir(directoryPath)
for entry in entries:
menuVoice = QStandardItem()
menuVoice.setData(entry, entryRole)
videoPath = os.path.join(directoryPath, entry)
menuVoice.setData(videoPath, addressRole)
Your QML seems inconsistent with what you want. In this case I have created a Menu within the MenuBar where the MenuItem will be created using the model and a Repeater:
import os
import sys
from PySide2 import QtCore, QtGui, QtQml
NameRole = QtCore.Qt.UserRole + 1000
PathRole = QtCore.Qt.UserRole + 1001
def create_model(dir_path):
model = QtGui.QStandardItemModel()
roles = {NameRole: b"name", PathRole: b"path"}
model.setItemRoleNames(roles)
for name in os.listdir(dir_path):
it = QtGui.QStandardItem()
it.setData(name, NameRole)
it.setData(os.path.join(dir_path, name), PathRole)
model.appendRow(it)
return model
def main(args):
app = QtGui.QGuiApplication(args)
current_dir = os.path.dirname(os.path.realpath(__file__))
video_dir = os.path.join(current_dir, "video")
model = create_model(video_dir)
engine = QtQml.QQmlApplicationEngine()
engine.rootContext().setContextProperty("video_model", model)
current_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(current_dir, "main.qml")
engine.load(QtCore.QUrl.fromLocalFile(filename))
if not engine.rootObjects():
return -1
ret = app.exec_()
return ret
if __name__ == "__main__":
sys.exit(main(sys.argv))
import QtQuick 2.13
import QtQuick.Controls 2.13
import QtMultimedia 5.13
ApplicationWindow {
id: root
width: 640
height: 480
visible: true
menuBar: MenuBar {
Menu {
id: plugins_menu
title: qsTr("&Videos")
Repeater{
model: video_model
MenuItem{
text: model.name
onTriggered: {
video.source = Qt.resolvedUrl(model.path)
video.play()
}
}
}
}
}
Video {
id: video
anchors.fill: parent
}
}
Hi i have the following problem :
this is my working code
import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
import os
import vlc
from time import sleep
# define VLC instance
instance = vlc.Instance()
# Define VLC player
instance = vlc.Instance('--input-repeat=-1', '--fullscreen')
player = instance.media_player_new()
list_test = []
list_name = []
def prepare_url(url):
media = instance.media_new(url)
player.set_media(media)
if __name__ == "__main__":
os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("main", engine)
engine.load('SimpleQML.qml')
win = engine.rootObjects()[0]
win.show()
button = win.findChild(QObject, "playBtn")
def myFunction():
print("A fine piece of text")
button.clicked.connect(myFunction) # works on click
myFunction() #works with out clicking
sys.exit(app.exec_())
Now i would like to expand on that by doing the following code :
import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
import os
import vlc
from time import sleep
# define VLC instance
instance = vlc.Instance()
# Define VLC player
instance = vlc.Instance('--input-repeat=-1', '--fullscreen')
player = instance.media_player_new()
list_test = []
list_name = []
def prepare_url(url):
media = instance.media_new(url)
player.set_media(media)
if __name__ == "__main__":
os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("main", engine)
engine.load('SimpleQML.qml')
win = engine.rootObjects()[0]
win.show()
button = win.findChild(QObject, "playBtn")
comboBox = win.findChild(QObject, "comboBox")
def myFunction():
print("das")
def list_fill():
with open("config/stations.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
list_t = [item.split("|")[0] for item in content if item]
list_n = [item.split("|")[1] for item in content if item]
del list_test[:]
del list_name[:]
comboBox.clear()
for x in list_t:
list_test.append(x)
for x in list_n:
list_name.append(x)
addItems(list_name)
button.clicked.connect(myFunction) # works too
myFunction()
list_fill() #calling this crashes program
sys.exit(app.exec_())
and at the very end this is the error
das
Traceback (most recent call last):
File "/home/flea/Desktop/quick qt/main.py", line 65, in <module>
list_fill()
File "/home/flea/Desktop/quick qt/main.py", line 55, in list_fill
comboBox.clear()
AttributeError: 'QObject' object has no attribute 'clear'
i tried to do ti with hardcoded list, but list is not the problem, for some reason my combo box is not recognized by python.I am not sure what is the problem here.
I can load my button and add a click event to it, (which works), but i cant add list to my comboBox.
here is my Qml
import QtQuick 2.10
import QtQuick.Controls 2.1
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.3
ApplicationWindow {
id: applicationWindow
Material.theme: Material.Light
title: qsTr("Test Invoke")
width: 600
height: 500
Row {
id: row
width: 200
height: 400
anchors.left: parent.left
anchors.leftMargin: 5
anchors.top: parent.top
anchors.topMargin: 5
Button{
id: playBtn
objectName: "playBtn"
text : "Play"
checked: false
padding: 6
rightPadding: 8
font.wordSpacing: 0
font.pointSize: 10
font.family: "Times New Roman"
topPadding: 4
highlighted: true
Material.accent: Material.Red
}
Button {
id: stopBtn
objectName: "stopBtn"
text: qsTr("Stop")
anchors.left: playBtn.right
anchors.leftMargin: 5
}
Button {
id: stfBtn
text: qsTr("Save")
objectName: "stfBtn"
anchors.left: stopBtn.right
anchors.leftMargin: 5
}
Button {
id: minimize
objectName: "minBtn"
text: qsTr("Min")
anchors.left: stfBtn.right
anchors.leftMargin: 5
}
}
Column {
id: column
x: 135
y: 100
width: 200
height: 400
TextField {
objectName: "nameText"
id: nameText
width: 300
text: qsTr("")
}
TextField {
objectName: "urlText"
id: urlText
width: 300
text: qsTr("")
}
ComboBox {
objectName: "comboBox"
id: comboBox
width: 200
}
}
Slider {
id: slide
objectName: "slider"
x: 160
y: 311
value: 0.5
}
}
It is not a good nor maintainable over time to instantiate an object created in QML from Python or C++.
The appropriate thing is to create an object in Python or C++ and send it to QML, and then create qproperties and slots that allow interacting with the QML.
In your case, I guess that list_fill tries to add data to the ComboBox, but the ComboBox does not have a clear method, so if you want to clean it, just pass it an empty list, or in your case pass it the new list.
On the other hand it is not elegant to call show(), it is best to set the visible property of ApplicationWindow to true.
main.py
import sys
import os
from PyQt5.QtCore import QObject, QUrl, Qt, pyqtSlot, pyqtSignal, pyqtProperty
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
import vlc
# define VLC instance
instance = vlc.Instance()
# Define VLC player
instance = vlc.Instance('--input-repeat=-1', '--fullscreen')
player = instance.media_player_new()
list_test = []
list_name = []
def prepare_url(url):
media = instance.media_new(url)
player.set_media(media)
class Manager(QObject):
stationsChanged = pyqtSignal()
currentStationChanged = pyqtSignal()
def __init__(self):
QObject.__init__(self)
self.m_stations = []
self.m_currentStation = ""
self.currentStationChanged.connect(self.on_currentStationChanged)
#pyqtProperty(str, notify=currentStationChanged)
def currentStation(self):
return self.m_currentStation
#currentStation.setter
def currentStation(self, val):
if self.m_currentStation == val:
return
self.m_currentStation = val
self.currentStationChanged.emit()
#pyqtProperty(list, notify=stationsChanged)
def stations(self):
return self.m_stations
#stations.setter
def stations(self, val):
if self.m_stations == val:
return
self.m_stations = val[:]
self.stationsChanged.emit()
#pyqtSlot()
def play(self):
print("play", self.currentStation)
#pyqtSlot()
def stop(self):
print("stop")
#pyqtSlot()
def on_currentStationChanged(self):
print(self.currentStation)
def list_fill(self):
l = []
with open("config/stations.txt") as f:
content = f.readlines()
content = [x.strip() for x in content]
list_t = [item.split("|")[0] for item in content if item]
list_n = [item.split("|")[1] for item in content if item]
l += list_t + list_n
self.stations = l
if __name__ == "__main__":
os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
manager = Manager()
ctx = engine.rootContext()
ctx.setContextProperty("Manager", manager)
engine.load('main.qml')
if not engine.rootObjects():
sys.exit(-1)
manager.list_fill()
sys.exit(app.exec_())
main.qml
import QtQuick 2.10
import QtQuick.Controls 2.1
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.3
ApplicationWindow {
id: applicationWindow
Material.theme: Material.Light
title: qsTr("Test Invoke")
visible: true
width: 600
height: 500
Row {
id: row
width: 200
height: 400
anchors.left: parent.left
anchors.leftMargin: 5
anchors.top: parent.top
anchors.topMargin: 5
Button{
id: playBtn
text : "Play"
checked: false
padding: 6
rightPadding: 8
font.wordSpacing: 0
font.pointSize: 10
font.family: "Times New Roman"
topPadding: 4
highlighted: true
Material.accent: Material.Red
onClicked: Manager.play()
}
Button {
id: stopBtn
text: qsTr("Stop")
anchors.left: playBtn.right
anchors.leftMargin: 5
onClicked: Manager.stop()
}
Button {
id: stfBtn
text: qsTr("Save")
objectName: "stfBtn"
anchors.left: stopBtn.right
anchors.leftMargin: 5
}
Button {
id: minimize
objectName: "minBtn"
text: qsTr("Min")
anchors.left: stfBtn.right
anchors.leftMargin: 5
}
}
Column {
id: column
x: 135
y: 100
width: 200
height: 400
TextField {
id: nameText
width: 300
text: qsTr("")
}
TextField {
id: urlText
width: 300
text: qsTr("")
}
ComboBox {
id: comboBox
width: 200
model: Manager.stations
onCurrentTextChanged: Manager.currentStation = currentText
}
}
Slider {
id: slider
x: 160
y: 311
value: 0.5
}
}
The advantage of this implementation is that you can modify the design and logic part independently. If you pass an object through setContextProperty it will be visible in all .qml files. With your previous approach you were going to have problems if you were going to have many .qml