Last active
August 22, 2017 14:54
-
-
Save spooky/ef430ebdf9d8034d157e6fa0994bb81b to your computer and use it in GitHub Desktop.
2 way qml binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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