Skip to content

Instantly share code, notes, and snippets.

@spooky
Last active August 22, 2017 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spooky/ef430ebdf9d8034d157e6fa0994bb81b to your computer and use it in GitHub Desktop.
Save spooky/ef430ebdf9d8034d157e6fa0994bb81b to your computer and use it in GitHub Desktop.
2 way qml binding
import sys
from PyQt5.QtCore import QObject, QUrl, pyqtSignal, pyqtSlot, pyqtProperty
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
class ViewModel(QObject):
text_changed = pyqtSignal(name='textChanged')
def __init__(self, *args, **kwargs):
self._text = kwargs.pop('text', None)
super().__init__(*args, **kwargs)
@pyqtProperty(str, notify=text_changed)
def text(self):
return self._text
@text.setter
def text(self, value):
if self._text != value:
self._text = value
self.text_changed.emit()
print('[py]', value)
@pyqtSlot()
def do_something(self):
self.text = 'something'
def start_ui():
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
viewModel = ViewModel(text='initial value')
rootContext = engine.rootContext()
rootContext.setContextProperty('viewModel', viewModel)
engine.load(QUrl('main.qml'))
return app.exec_()
if __name__ == '__main__':
sys.exit(start_ui())
import QtQuick 2.7
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import QtQuick.Dialogs 1.2
ApplicationWindow {
id: mainWindow
visible: true
width: 400
height: 150
title: qsTr("qml zaczyna smierdziec")
RowLayout {
anchors.centerIn: parent
TextField {
id: txtField
text: viewModel.text
onTextChanged: viewModel.text = text;
}
Button {
text: "do"
onClicked: {
viewModel.do_something();
console.log('[qml]', txtField.value)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment