在您提供的示例中,没有观察到优势,因此您认为它是多余的。
在某些应用程序中,需要有多个源,并且副本必须连接到每个源是多余的,因此 QRemoteObjectRegistryHost 的任务是为多个源提供一个连接点,并通过它连接副本。
例如,以下方案显示了它的用途:
┌-------------------┐ ┌-------------------┐
| QRemoteObjectHost | | QRemoteObjectHost |
└--------┬----------┘ └-------┬-----------┘
| |
| |
┌----┴-----------------------------------┴----┐
| QRemoteObjectRegistryHost |
└--┬-------------------┬-----------------┬----┘
| | |
| | |
┌-------┴----- ---┐ ┌-------┴---------┐ ┌-----┴------- ---┐
|QRemoteObjectNode| |QRemoteObjectNode| |QRemoteObjectNode|
└-----------------┘ └-----------------┘ └-----------------┘
通过 可以注册多个节点QRemoteObjectHost
,并在QRemoteObjectHost
中注册,QRemoteObjectRegistryHost
以便任何人都可以通过 获取节点QRemoteObjectNode
的副本。QRemoteObjectHost
QRemoteObjectRegistryHost
为了说明我创建了以下示例的功能:
├── register.py
├── replica.py
└── source.py
注册.py
from PyQt5 import QtCore, QtRemoteObjects
if __name__ == "__main__":
import sys
app = QtCore.QCoreApplication(sys.argv)
regNode = QtRemoteObjects.QRemoteObjectRegistryHost(
QtCore.QUrl("tcp://127.0.0.1:5557")
)
sys.exit(app.exec_())
副本.py
from functools import partial
import sys
from PyQt5 import QtCore, QtRemoteObjects
if __name__ == "__main__":
app = QtCore.QCoreApplication(sys.argv)
node = QtRemoteObjects.QRemoteObjectNode(QtCore.QUrl("tcp://127.0.0.1:5557"))
replicas = []
def on_remoteObjectAdded(info):
name, url = info
print("object added", name, url)
replica = node.acquireDynamic(name)
wrapper = partial(on_initialized, replica, name)
replica.initialized.connect(wrapper)
replicas.append(replica)
node.registry().remoteObjectAdded.connect(on_remoteObjectAdded)
def on_initialized(replica, name):
wrapper = partial(print, name)
replica.dataChanged.connect(wrapper)
sys.exit(app.exec_())
源码.py
import sys
from PyQt5 import QtCore, QtRemoteObjects
class Node(QtCore.QObject):
dataChanged = QtCore.pyqtSignal(str)
if __name__ == "__main__":
app = QtCore.QCoreApplication(sys.argv)
parser = QtCore.QCommandLineParser()
parser.addPositionalArgument("url", "Host URL different to tcp://127.0.0.1:5557")
parser.addPositionalArgument("name", "Name of node")
parser.process(app)
args = parser.positionalArguments()
if len(args) != 2:
print("only url and name is required")
sys.exit(-1)
url, name = args
if QtCore.QUrl("tcp://127.0.0.1:5557") == QtCore.QUrl(url):
print("url different tcp://127.0.0.1:5557")
sys.exit(-1)
node = Node()
srcNode = QtRemoteObjects.QRemoteObjectHost(
QtCore.QUrl(url), QtCore.QUrl("tcp://127.0.0.1:5557")
)
srcNode.enableRemoting(node, name)
def on_timeout():
data = QtCore.QDateTime.currentDateTime().toString()
node.dataChanged.emit(data)
timer = QtCore.QTimer(interval=1000, timeout=on_timeout)
timer.start()
sys.exit(app.exec_())
然后在不同的 CMD/终端上运行以下命令:
python register.py
python replica.py
python source.py tcp://127.0.0.1:5558 node1
python source.py tcp://127.0.0.1:5559 node2
在 replica.py 的 CMD/终端控制台中,您将看到以下内容:
# ...
node1 Tue Jan 7 22:32:09 2020
node2 Tue Jan 7 22:32:09 2020
node1 Tue Jan 7 22:32:10 2020
node2 Tue Jan 7 22:32:10 2020
# ...