使用PyQT通过套接字传输文件的确认框

时间:2011-10-27 23:31:32

标签: python pyqt pyqt4

我有一个确认框,在通过网络发送文件时会被调用。但是,Signal的函数位于MainWindow类中,并使用Worker线程中的变量。但它不起作用,因为工作线程中的变量不在正确的范围内。

知道如何将msg变量传递给信号中saveFile类的MainWindow函数吗?

编辑:我需要做的是将一个参数传递给我的信号,但我想出来了。对困惑感到抱歉。我不确定需要做什么。

这是一个有效的例子:

import socket
import select
import sys, os
from PyQt4.QtCore import * 
from PyQt4.QtGui import *

CMD_FILE = 1

CLIENT_PORT = 9001
CLIENT_HOST = '127.0.0.1'

class MainWindow(QWidget):
    def __init__(self, parent=None):
        #super(QWidget, self).__init__(parent)
        super(MainWindow, self).__init__(parent)
        self.resize(100, 50)
        self.thread = Worker()
        self.thread.start()

        self.file_button = QPushButton('Send a File')
        self.connect(self.file_button, SIGNAL("released()"), self.sendFile)

        self.connect_button = QPushButton('Connect To Server')
        self.connect(self.connect_button, SIGNAL("released()"), self.connectToServer)

        self.connect(self.thread, SIGNAL('triggered(PyQt_PyObject)'), self.saveFile)
        self.layout = QFormLayout()
        self.layout.addRow(self.file_button, self.connect_button)

        self.setLayout(self.layout)

    def connectToServer(self):
        global s
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((str(CLIENT_HOST).strip(), CLIENT_PORT))
            print "Connected to ", str(CLIENT_HOST)
        except:
            print "unable to connect"

    def clientAll(self, cmd, msg):
        #check if connnected send a message
        s.sendall(cmd + msg)

    def sendFile(self):
        filename=QFileDialog.getOpenFileName(self, 'Open File', '.')
        f = open(filename, 'rb')
        myFile = f.read()
        self.clientAll(chr(CMD_FILE), myFile)
        f.close()
        print filename, "Sent\n"

    def saveFile(self, msg):
        reply = QMessageBox.question(self, 'Message',
            "Are you sure you wish to download this file?", QMessageBox.Yes | 
            QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            filename = QFileDialog.getSaveFileName(self, 'Save File', '.')
            f = open(filename, 'wb')
            f.write(msg)
            f.close()
            print filename, "Recieved"
        else:
            pass

class Worker(QThread):
    def __init__(self):
        QThread.__init__(self)
        self.exiting = False

    def __del__(self):
        self.exiting = True
        self.wait()

    def run(self):
        source_ip = ''
        #socket.gethostbyname(socket.gethostname())
        PORT = 9001
        ### Initialize socket
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind((source_ip, PORT))
        # 
        server_socket.listen(5)
        read_list = [server_socket]
        ### Start receive loop
        while True:
            readable, writable, errored = select.select(read_list, [], [])
            for s in readable:
                if s is server_socket:
                    conn, addr = s.accept()
                    read_list.append(conn)
                else:
                    msg = conn.recv(12024)
                    if msg:                
                        cmd, msg = ord(msg[0]),msg[1:]
                        if cmd == CMD_FILE:
                            if not msg: break
                            self.emit(SIGNAL('triggered(PyQt_PyObject)'), msg)
                    else:
                        s.close()
                        read_list.remove(s)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()
    win.setWindowTitle('CATS!!! <3')
    win.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

我想我完全不了解你的情况 但是,您是否尝试定义新的(自定义)信号? 如果使用 pyqtSignal 定义新信号,
你可以用参数发出信号。

Documentation on signal and slots (new style)