【发布时间】:2019-07-10 21:10:28
【问题描述】:
我正在使用 PyQt5 和 Qml 创建客户端应用程序。这是我的 Qml 文件的简化示例:
import QtQuick 2.11
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
ApplicationWindow {
visible: true
width: Screen.width/2
height: Screen.height/2
Rectangle {
id: rectangle
x: 187
y: 92
width: 200
height: 200
color: "blue"
}
}
客户端应用程序必须从服务器接收上述矩形的属性。为了做到这一点,我在“.py”文件中实现了一个套接字连接。 client.py 文件应该从服务器实时接收信息。我受到聊天应用程序的启发,我使用 (while True:{}) 循环来执行此操作:
from PyQt5.QtQml import QQmlApplicationEngine, QQmlProperty
from PyQt5.QtQuick import QQuickWindow, QQuickView
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtWidgets import QApplication
import sys, socket
def run():
myApp = QApplication(sys.argv)
myEngine = QQmlApplicationEngine()
myEngine.load('mainViewofHoomanApp.qml')
Win = myEngine.rootObjects()[0]
rect = Win.findChild(QObject, "rectangle")
rect.setProperty("height", 10) # Here I am accessing the properties of the rectangle
if not myEngine.rootObjects():
return -1
return myApp.exec_()
if __name__ == "__main__":
sys.exit(run())
而且是socket连接的格式:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Server_IPAddress = '192.168.1.163'
Port = 5000
client_socket.connect((Server_IPAddress,Port))
while True:
message = client_socket.recv(1024)
# Then the code extracts the parameters from the message
# and converts it to integer, and saves it in realT_width variable:
rect.setProperty("height", realT_width variable)
我对如何将这两个代码合并在一起感到困惑。如果我在编写 myApp.exec_() 命令后调用套接字连接,则 QML 文件将不再对参数更改命令作出反应。另一方面,如果我在 QML 执行之前编写套接字连接,那么 while 循环将不允许执行后面的代码行。
【问题讨论】:
-
显示你的服务器代码
-
服务器代码是用 Csharp 编写的,不幸的是,我无法访问它。但它会发送一个包含所需参数值的字符串。
-
好的,我将发布我的答案一个简单的服务器代码,我将使用它来测试我的代码
-
太棒了。谢谢
标签: python sockets pyqt qml real-time