Python通过网络自动同步表

时间:2014-04-27 21:27:30

标签: python networking pyqt

我有两个程序都带有QTableWidget。我想自动通过网络同步表。我不知道该怎么做。我已经使用了pyqt和套接字它已经工作了。我已经阅读了很多关于simple chat application like this的内容。我认为这不是我需要的方式。

我的程序没有任何网络代码:

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):

        QtGui.QMainWindow.__init__(self, parent)

        # Table
        header = ["Name", "Date", "Club"]

        self.Table = QtGui.QTableWidget(0, len(header))
        self.Table.setHorizontalHeaderLabels(header)
        self.Table.resizeColumnsToContents()

        # Layout
        layout = QtGui.QGridLayout()
        layout.addWidget(self.Table)

        self.tab_widget = QtGui.QTabWidget()
        self.tab_widget.updatesEnabled()

        tabs = [u"Overview"]
        for i,d in enumerate(tabs):
            widget = QtGui.QWidget()
            self.tab_widget.addTab(widget, d)
            print i, d
            if i == 0:
                widget.setLayout(layout)

        self.setCentralWidget(self.tab_widget)
        self.show()

        data = ["Name1", "Monday", "Club1"]

        self.Table.insertRow(0)

        # insert Data
        for i in range(len(data)):

            t = QtGui.QTableWidgetItem(data[i].decode("utf8"))
            self.Table.setItem(0, i, t)

        self.Table.resizeColumnsToContents()                    

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    prog = Window()
    prog.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

我建议更改QTable以使用模型而不是项目。有关基于列表列表的示例,请参阅here,列表列表应易于更改为词典列表(如果您选择)。

下面的代码使用JSON和ZeroMQ到JSON-serialise词典,并将它们推送到侦听器以更新字典。

import json
import time
import threading
import zmq

class push_to(object):
    def __init__(self, address, *args, **kwargs):
        context = zmq.Context()

        # Socket to send messages to
        self.sender = context.socket(zmq.PAIR)
        self.sender.connect(address)

    def __call__(self, send_str, *args, **kwargs):
        self.sender.send_string(send_str)

class own_listener(threading.Thread):
    def __init__(self, parent, address, *args, **kwargs):
        self.parent = parent

        context = zmq.Context()

        # Socket to receive messages from
        self.receiver = context.socket(zmq.PAIR)
        self.receiver.bind(address)
        super(own_listener, self).__init__(*args, **kwargs)
        self.daemon = True

    def run(self):
        while True:
            message = self.receiver.recv()
            self.parent.change_receive(message)

class pub_sub_dict(dict):
    def __init__(self, address, *args, **kwargs):
        self.address   = address
        self.listeners = []
        self.is_listen = False
        super(pub_sub_dict, self).__init__(*args, **kwargs)
        self.own_listener = own_listener(self, address)
        self.own_listener.start()

    def __setitem__(self, key, value, *args, **kwargs):
        if not self.is_listen:
            self.change_send({key : value})
        super(pub_sub_dict, self).__setitem__(key, value, *args, **kwargs)

    def update(self, value, *args, **kwargs):
        if not self.is_listen:
            self.change_send(value)
        super(pub_sub_dict, self).update(value, *args, **kwargs)

    def change_send(self, idict):
        json_str = json.JSONEncoder().encode(idict)
        for listener in self.listeners:
            listener(json_str)

    def change_receive(self, json_str):
        self.is_listen = True
        state = json.JSONDecoder().decode(json_str)
        self.update(state)
        self.is_listen = False

a = pub_sub_dict("tcp://127.0.0.1:5556")
b = pub_sub_dict("tcp://127.0.0.1:5557")
c = pub_sub_dict("tcp://127.0.0.1:5558")

a.listeners.append(push_to(b.address))
a.listeners.append(push_to(c.address))
b.listeners.append(push_to(a.address))

print "a:", a
print "b:", b
print "c:", c
time.sleep(1)
a["test"] = "test string 1"
print "a:", a
print "b:", b
print "c:", c
time.sleep(1)
b["test"] = "test string 2"
print "a:", a
print "b:", b
print "c:", c
time.sleep(1)