如何将 Qt Quick 中的按钮绑定到 Python PyQt 5 [英] How to bind buttons in Qt Quick to Python PyQt 5

查看:56
本文介绍了如何将 Qt Quick 中的按钮绑定到 Python PyQt 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将我在 .qml 脚本中创建的按钮绑定到 python PyQt5 代码?

How can bind the buttons I create in a .qml script to python PyQt5 code?

示例:蟒蛇:

import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine

if __name__ == "__main__":
  app = QApplication(sys.argv)
  engine = QQmlApplicationEngine()
  ctx = engine.rootContext()
  ctx.setContextProperty("main", engine)

  engine.load('test.qml')

  win = engine.rootObjects()[0]
  win.show()
  sys.exit(app.exec_())

qml:

import QtQuick 2.2
import QtQuick.Window 2.1
import QtQuick.Controls 1.2
import QtQuick.Dialogs 1.1

ApplicationWindow {
 title: qsTr("Test Invoke")

 width: 200
 height: 100

 Button{
  y : 70
  text : "About"
  onClicked: {
   print('Hello')
  }

 }
}

单击按钮时如何使用 Python 执行某些操作?另外:有没有人有很好的示例或文档资源.关于 pyqt + qml (qt quick)?

How can I do something with Python when the button is clicked? Also: Does anyone has a good resource of examples or doc. about pyqt + qml (qt quick)?

推荐答案

如果为按钮命名,则可以连接到它的 onClick 信号,或者连接到它在 onClicked 中发出的自定义信号.示例:

If you name the button, you can connect to its onClick signal, or to a custom signal that it emits in onClicked. Example:

ApplicationWindow {
 title: qsTr("Test Invoke")
 width: 200
 height: 100

 Button {
  signal messageRequired
  objectName: "myButton"
  y : 70
  text : "About"
  onClicked: messageRequired()

 }
}

注意 Button 中的信号和 objectName 属性.那么 exec 之前的 Python 代码可以是例如:

Note the signal in Button and the objectName property. Then the Python code just before exec could be for example:

def myFunction():
    print 'handler called'

button = win.findChild(QObject, "myButton")
button.messageRequired.connect(myFunction)
button.clicked.connect(myFunction) # works too

注意,在上面的Button中,onClicked只是发出messageRequired信号,所以最好去掉自定义信号并连接到clicked> 直接.onClicked() 和任何连接到 clicked 的插槽都将在您单击按钮时被调用.

Note that in the Button above, onClicked just emits the messageRequired signal, so it is better to drop the custom signal and connect to clicked directly. Both onClicked() and any slots connected to clicked will get called when you click button.

这篇关于如何将 Qt Quick 中的按钮绑定到 Python PyQt 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆