当前位置: 首页>>代码示例>>Python>>正文


Python QThread.start方法代码示例

本文整理汇总了Python中PySide.QtCore.QThread.start方法的典型用法代码示例。如果您正苦于以下问题:Python QThread.start方法的具体用法?Python QThread.start怎么用?Python QThread.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PySide.QtCore.QThread的用法示例。


在下文中一共展示了QThread.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _btnTransferClicked

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
 def _btnTransferClicked(self):
     'Transfer Dives'
     idx = self._cbxComputer.currentIndex()
     dc = self._cbxComputer.itemData(idx, Qt.UserRole+0)
     
     if self._logbook.session.dirty:
         print "Flushing dirty session"
         self._logbook.rollback()
     
     self._txtLogbook.setEnabled(False)
     self._btnBrowse.setEnabled(False)
     self._cbxComputer.setEnabled(False)
     self._btnAddComputer.setEnabled(False)
     self._btnRemoveComputer.setEnabled(False)
     self._btnTransfer.setEnabled(False)
     self._btnExit.setEnabled(False)
     
     self._txtStatus.clear()
     
     thread = QThread(self)
     
     #FIXME: ZOMG HAX: Garbage Collector will eat TransferWorker when moveToThread is called
     #NOTE: Qt.QueuedConnection is important...
     self.worker = None
     self.worker = TransferWorker(dc)
     thread.started.connect(self.worker.start, Qt.QueuedConnection)
     self.worker.moveToThread(thread)
     self.worker.finished.connect(self._transferFinished, Qt.QueuedConnection)
     self.worker.finished.connect(self.worker.deleteLater, Qt.QueuedConnection)
     self.worker.finished.connect(thread.deleteLater, Qt.QueuedConnection)
     self.worker.progress.connect(self._transferProgress, Qt.QueuedConnection)
     self.worker.started.connect(self._transferStart, Qt.QueuedConnection)
     self.worker.status.connect(self._transferStatus, Qt.QueuedConnection)
     
     thread.start()
开发者ID:asymworks,项目名称:python-divelog,代码行数:37,代码来源:qdcxfer.py

示例2: start_q_watcher

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
def start_q_watcher(app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em):
    # need to spawn a worker thread that watches the proc_comms_q
    # need to seperate queue function from queue thread
    # http://stackoverflow.com/questions/4323678/threading-and-signals-problem
    # -in-pyqt
    q_watcher = QueueWatcher(
        app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em)
    q_watcher_thread = QThread()
    q_watcher.moveToThread(q_watcher_thread)
    q_watcher_thread.started.connect(q_watcher.check_queue)

    # now that we've set up the thread, let's set up rest of signals/slots
    q_watcher.set_out_enable.connect(emu_window.set_output_enable)
    q_watcher.set_out_disable.connect(emu_window.set_output_disable)
    q_watcher.get_in.connect(emu_window.get_input)
    q_watcher.get_out.connect(emu_window.get_output)

    emu_window.send_output.connect(q_watcher.send_get_out_pin_result)
    emu_window.send_input.connect(q_watcher.send_get_in_pin_result)
    emu_window.interrupt_flagger.connect(q_watcher.handle_interrupt)

    # not sure why this doesn't work by connecting to q_watcher_thread.quit
    def about_to_quit():
        q_watcher_thread.quit()
    app.aboutToQuit.connect(about_to_quit)

    q_watcher_thread.start()
开发者ID:math4youbyusgroupillinois,项目名称:LN_Digital_Emulator,代码行数:29,代码来源:gui.py

示例3: QApplicationRunner

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
class QApplicationRunner(QObject):
    """ Application runner starts application in own thread """
    def __init__(self):
        QObject.__init__(self)
        self._thread = QThread()
        self.moveToThread(self._thread)
        self._thread.started.connect(self.start)
        self._ev = Event()
        self._app = None
        self._thread.start()

    @Slot()
    def start(self):
        self.app = Application()
        self._ev.set()
        self.app.exec_()

    def exit(self):
        self.app.exit() # perform polite disposal of resources
        if self._thread.isRunning():
            self._thread.wait(1000) # wait 1 sec
            self._thread.terminate() # no-way

    @property
    def app(self):
        if not self._ev.isSet():
            self._ev.wait()
        return self._app
    @app.setter
    def app(self, app):
        self._app = app
开发者ID:pborky,项目名称:webkit-scraper,代码行数:33,代码来源:webkit_scraper.py

示例4: _refresh

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
    def _refresh(self):
        'Refresh the list of Computers'
        self._btnRefresh.setEnabled(False)
        self._btnRefresh.setText('Scanning...')
        self._model.clear()
        
        typ = self.wizard().field('type')
        if typ == len(ComputerTypes):
            # Custom Computer Type
            didx = self.wizard().field('driver')
            drvr = list_drivers().keys()[didx]
            dopt = self.wizard().field('driveropt')
        else:
            # Predefined Computer Type
            drvr = ComputerTypes[typ]['driver']
            dopt = ComputerTypes[typ]['driveropt']
        
        dclass = list_drivers()[drvr]['class']
        doptions = [] if dopt == '' else dopt.split(':')
        
        thread = QThread(self)
        
        #FIXME: ZOMG HAX: Garbage Collector will eat DiscoveryWorker when moveToThread is called
        #NOTE: Qt.QueuedConnection is important...
        self.worker = None
        self.worker = DiscoveryWorker(dclass, doptions)
        self.worker.moveToThread(thread)
        thread.started.connect(self.worker.start, Qt.QueuedConnection)
        self.worker.foundDevice.connect(self._model.addItem, Qt.QueuedConnection)
        self.worker.finished.connect(self._discoverFinished, Qt.QueuedConnection)
        self.worker.finished.connect(self.worker.deleteLater, Qt.QueuedConnection)
        self.worker.finished.connect(thread.deleteLater, Qt.QueuedConnection)

        thread.start()
开发者ID:asymworks,项目名称:python-divelog,代码行数:36,代码来源:add_dc.py

示例5: QWebPageRunner

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
class QWebPageRunner(QObject):
    """ Web page runner starts WebPage instances in one separate thread and implements custom event loop. """
    #FIXME: consider using QEventLoop instead
    def __init__(self, app):
        QObject.__init__(self)
        self._thread = QThread()
        self.moveToThread(self._thread)
        self._thread.started.connect(self.start)
        self._destroying = Event()
        self._destroying.clear()
        self._result = None
        self._commandQueue = Queue()
        self._app = app
        self._thread.start()

    @Slot()
    def start(self):
        try:
            while not self._destroying.is_set():
                self._app.processEvents()
                try:
                    cmd = self._commandQueue.get(timeout=0.1)
                    args = ()
                    if isinstance(cmd, tuple):
                        if not len(cmd):
                            continue
                        args = cmd[1:]
                        cmd = cmd[0]
                    if isinstance(cmd, NewPage):
                        args = (self._app,)
                    if isinstance(cmd, Command):
                        cmd(*args)
                    else:
                        raise ValueError('Unknown command %s(%s).' % (cmd, args))
                except Empty:
                    pass
        except Exception as e:
            logger.exception(e)

    def exit(self):
        self._destroying.set()
        if self._thread.isRunning():
            self._thread.wait(1000) # wait 1 sec
            self._thread.terminate() # no-way

    def invoke(self, cmd, *args):
        if isinstance(cmd, type) and issubclass(cmd, Command):
            cmd = cmd()
        if not isinstance(cmd, Command):
            cmd = Command(cmd)
        cmd.event.clear()
        self._commandQueue.put((cmd,)+args)
        while not cmd.event.is_set():
            self._app.processEvents()
            cmd.event.wait(0.1)
        return cmd.result
开发者ID:pborky,项目名称:webkit-scraper,代码行数:58,代码来源:webkit_scraper.py

示例6: main

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
def main():

    loadtesterplugins()

    qt.mainthread = QThread.currentThread()  # Store current thread
    qt.initialize_view()  # Get the view ready
    dispatch_thread = QThread()  # The QThread to put the dispatcher on
    qt.maindispatch = QTDispatcher(qt.mainview)  # Set up the dispatcher
    qt.qapp.lastWindowClosed.connect(dispatch_thread.quit)  # Connect the close signal to the thread quit signal
    qt.maindispatch.moveToThread(dispatch_thread)  # Move the dispatcher to the new thread
    dispatch_thread.start()  # Start the thread
    qt.mainview.show()  # Show the main window
    res = qt.qapp.exec_()  # Start the event loop, exits when the last window has been closed
    dispatch_thread.wait()  # Wait for the dispatcher thread to finish
    sys.exit(res)
开发者ID:DragonFire168,项目名称:MoodleGradeTool,代码行数:17,代码来源:qgrade.py

示例7: start_input_watcher

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
def start_input_watcher(app, emu_window):
    input_watcher = InputWatcher()
    input_watcher_thread = QThread()
    input_watcher.moveToThread(input_watcher_thread)
    input_watcher_thread.started.connect(input_watcher.check_inputs)
    
    # signal / slots
    input_watcher.set_in_enable.connect(emu_window.set_input_enable)
    input_watcher.set_in_disable.connect(emu_window.set_input_disable)

    # qyit setup
    def about_to_quit():
        input_watcher_thread.quit()
    app.aboutToQuit.connect(about_to_quit)

    input_watcher_thread.start()
开发者ID:kahira,项目名称:pifacedigital-emulator,代码行数:18,代码来源:pfemgui.py

示例8: start_interface_message_handler

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
def start_interface_message_handler(
        app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em):
    # need to spawn a worker thread that watches the proc_comms_q
    # need to seperate queue function from queue thread
    # http://stackoverflow.com/questions/4323678/threading-and-signals-problem
    # -in-pyqt
    handler_start = threading.Barrier(2)
    intface_msg_hand = InterfaceMessageHandler(
        app, proc_comms_q_to_em, proc_comms_q_from_em, handler_start)
    intface_msg_hand_thread = QThread()
    intface_msg_hand.moveToThread(intface_msg_hand_thread)
    intface_msg_hand_thread.started.connect(intface_msg_hand.check_queue)

    # now that we've set up the thread, let's set up rest of signals/slots
    intface_msg_hand.set_viewport_corner.connect(
        emu_window.slot_set_viewport_corner)
    intface_msg_hand.set_cursor.connect(emu_window.slot_set_cursor)
    intface_msg_hand.set_message.connect(emu_window.slot_set_message)
    intface_msg_hand.set_display_enable.connect(
        emu_window.slot_set_display_enable)
    intface_msg_hand.set_backlight_enable.connect(
        emu_window.slot_set_backlight_enable)
    intface_msg_hand.set_cursor_enable.connect(
        emu_window.slot_set_cursor_enable)
    intface_msg_hand.set_blink_enable.connect(
        emu_window.slot_set_blink_enable)
    intface_msg_hand.get_switch.connect(emu_window.slot_get_switch)
    intface_msg_hand.get_cursor.connect(emu_window.slot_get_cursor)
    intface_msg_hand.get_viewport_corner.connect(
        emu_window.slot_get_viewport_corner)
    intface_msg_hand.move_left.connect(emu_window.slot_move_left)
    intface_msg_hand.move_right.connect(emu_window.slot_move_right)
    intface_msg_hand.home.connect(emu_window.slot_home)
    intface_msg_hand.clear.connect(emu_window.slot_clear)
    intface_msg_hand.see_cursor.connect(emu_window.slot_see_cursor)

    emu_window.send_switch.connect(intface_msg_hand.send_get_switch_result)
    emu_window.send_cursor.connect(intface_msg_hand.send_get_cursor_result)
    emu_window.send_viewport_corner.connect(
        intface_msg_hand.send_get_viewport_corner_result)

    def about_to_quit():
        intface_msg_hand_thread.quit()
    app.aboutToQuit.connect(about_to_quit)

    intface_msg_hand_thread.start()
    handler_start.wait()
开发者ID:piface,项目名称:pifacecad-emulator,代码行数:49,代码来源:watchers.py

示例9: start_blinker

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
def start_blinker(app, emu_window):
    # need to spawn a worker thread that watches the proc_comms_q
    # need to seperate queue function from queue thread
    # http://stackoverflow.com/questions/4323678/threading-and-signals-problem
    # -in-pyqt
    blinker_start = threading.Barrier(2)
    blinker = Blinker(emu_window, blinker_start)
    blinker_thread = QThread()
    blinker.moveToThread(blinker_thread)
    blinker_thread.started.connect(blinker.blink)

    blinker.blink_signal.connect(emu_window.blink)

    # not sure why this doesn't work by connecting to blinker_thread.quit
    def about_to_quit():
        blinker_thread.quit()
    app.aboutToQuit.connect(about_to_quit)

    blinker_thread.start()
    blinker_start.wait()
开发者ID:piface,项目名称:pifacecad-emulator,代码行数:22,代码来源:watchers.py

示例10: main

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
def main(argv = None):
    if argv is None:
        argv = sys.argv

    version = '20130216'      # modification date in yyyymmdd format

    connmgr = ConnectionManager()
    comm = SerialComm(connmgr)
    app = QApplication(argv)
    appwindow = MainWindow(connmgr, 'Projector Control Panel')
    commthread = QThread()

    comm.enumerateSerialPorts()
    comm.moveToThread(commthread)
    commthread.start()

    appwindow.show()
    appwindow.writeToLog('Software version ' + version + '.')

    result = app.exec_()
    commthread.quit()
    commthread.wait()

    return result
开发者ID:jdeguire,项目名称:pjcontroller,代码行数:26,代码来源:main.py

示例11: UnlockDialog

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]

#.........这里部分代码省略.........

        return None


    def _checkScriptNameInFolder(self):
        parentProcessName = psutil.Process(os.getpid()).parent().name()
        if parentProcessName != "python.exe":
            scriptName = parentProcessName
        else:
            scriptName = os.path.basename(__file__)
        # get script name without extension
        scriptName = os.path.splitext(scriptName)[0]
        # change extension of script name to lock to .exelocker
        scriptName = scriptName + ".exelocker"
        # print scriptName
        fileList = self._getRelevantFilesInFolder()
        try:
            index = fileList.index(scriptName)
            print index
        except ValueError:
            index = None
        if index != None:
            return True
        else:
            return False

    def listWidgetSelectedEvent(self):
        self.fileName = self.listWidget.currentItem().text()
        self.setUnlockTextLabel(self.fileName)
        self.stackedWidget.setCurrentIndex(0)
        self.setUnlockTextLabel(self.fileName)

    def setUnlockTextLabel(self, fileName):
        if fileName and len(fileName):
            fileName = os.path.basename(fileName)
            string = u"Enter password for " + fileName + ":"
            self.unlockTextLabel.setText(string)

    def fillListWidget(self, location = None):
        if location != None:
            filteredList = self._getRelevantFilesInFolder(location)
        else:
            filteredList = self._getRelevantFilesInFolder()

        self.listWidget.addItems(filteredList)

    def _getRelevantFilesInFolder(self, location = None):
        if location == None:
            files = os.listdir('.')
        else:
            files = os.listdir(location)
        filteredList = []
        for f in files:
            if os.path.isfile(f):
                extension = os.path.splitext(f)[1]
                if extension == ".exelocker":
                    filteredList.append(f)
        return filteredList

    def browseFiles(self):
        dir = "."
        file = QFileDialog.getOpenFileName(self, "Select .exelocker file", dir, "EXE Locker file (*.exelocker)")
        if len(file[0]):
            self.fileName = file[0]
            self.stackedWidget.setCurrentIndex(0)
            self.setUnlockTextLabel(self.fileName)

    def fileUnlockedEvent(self, success, decryptedFileName):
        if success == 'True':
            QMessageBox.information(self, __appname__, "File Unlocked Successfully.")
        else:
            os.remove(decryptedFileName)
            EncryptedFile.replaceWithUnlockDialog(EncryptedFile.CALLER_LOCATION, decryptedFileName)
            QMessageBox.information(self, __appname__, "Wrong password. Couldn't unlock file.")

    def unlockFile(self):
        if EncryptedFile.isValidFile(self.fileName):
            eFile = EncryptedFile(self.fileName)
            unhashedPassword = self.passwordLineEdit.text()
            password = EncryptionHelper.generateKeyHash(unhashedPassword)
            self.thread = QThread()
            self.worker = Worker(eFile, password, self.signal, self.sameLocation)
            self.worker.moveToThread(self.thread)
            self.thread.started.connect(self.worker.run)
            self.worker.signal.connect(self.thread.quit)
            self.worker.signal.connect(self.worker.deleteLater)
            self.thread.finished.connect(self.thread.deleteLater)
            self.thread.start()
        else:
            QMessageBox.information(self, __appname__, "Invalid .exelocker file.")
        self.passwordLineEdit.setText("")



    def _getRelevantCmdArgument(self, args):
        for arg in args:
            if EncryptedFile.isValidFile(arg):
                return args.index(arg)

        return None
开发者ID:stirredo,项目名称:EXE-locker,代码行数:104,代码来源:UnlockDialog.py

示例12: MainWindow

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
class MainWindow(QMainWindow, Ui_MainWindow):

    add_name_signal = Signal(unicode)

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        # Create the name manager instance and move it to another thread.
        # This will cause all the slots to be run in that other thread
        # instead of our GUI thread.
        self.name_manager = NameManager()
        self.name_manager_thread = QThread()
        self.name_manager.moveToThread(self.name_manager_thread)
        self.name_manager_thread.start()

        # Create our network manager
        self.network_manager = NetworkManager()

        # When the name manager emits it's full name list, we want to
        # repopulate our list.
        self.name_manager.names_signal.connect(self.populate_list)

        # When the restore list button is clicked, let the name manager
        # know we need all the names in long term storage
        self.restore_list_button.clicked.connect(self.name_manager.get_all_names)

        self.add_name_signal.connect(self.name_manager.store_name)
        self.add_name_signal.connect(self.cache_name)
        self.submit_button.clicked.connect(self.say_hello)
        self.clear_list_button.clicked.connect(self.clear_list)

    def clean_up(self):
        """
        You can't rely on __del__ properly closing down all your threads. So use
        a clean_up method that will be called manually.
        :return:
        """
        if hasattr(self, 'network_manager_thread'):
            self.network_manager.api.end_connection()
            self.network_manager.api.join()
            self.network_manager_thread.quit()

        self.name_manager_thread.quit()

    def start_api(self, ip, port):
        """
        Connect to an external API service which will send us names
        :param ip: IP address of server
        :param port: Port of service
        :return:
        """
        self.network_manager_thread = QThread()
        self.network_manager.moveToThread(self.network_manager_thread)
        self.network_manager.message_signal.connect(self.handle_message)
        self.network_manager_thread.start()

        self.network_manager.connect_signal.emit(ip, port)

    @Slot()
    def handle_message(self, message):
        """
        Handle incoming names from the API. We simply want to follow the
        established procedure to add a new name. So we just emit on that
        signal.
        :param message: String name
        :return:
        """
        self.add_name_signal.emit(message)

    @Slot()
    def say_hello(self):
        self.add_name_signal.emit(self.name_text.text())
        self.hello_label.setText(u"{} {}".format(GREETING, self.name_text.text()))
        self.name_text.setText('')

    @Slot()
    def cache_name(self, name):
        self.names_list.addItem(name)

    @Slot()
    def clear_list(self):
        self.names_list.clear()

    @Slot()
    def populate_list(self, names):
        """
        Clears and repopulates the list with the given list
        :param names: List of names
        :return:
        """
        self.clear_list()
        for name in names:
            self.names_list.addItem(name)
开发者ID:CuriousLLC,项目名称:QtTestMethods,代码行数:96,代码来源:main.py

示例13: start

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
	def start(self):
		QThread.start(self)
		loop=QEventLoop()
		self._init.connect(loop.quit)
		loop.exec_()
开发者ID:MrP01,项目名称:SymbolWorte,代码行数:7,代码来源:Progress.py

示例14: Progress

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]

#.........这里部分代码省略.........
        self.init_vector = hashlib.sha256(str(self.init_vector).encode('utf-8')).hexdigest()
        self.init_vector = bytearray.fromhex(self.init_vector)[:16]

    """
    --------------------------------------------------------------------------------------------------------------------
    Create the Cipher Algorithm
    --------------------------------------------------------------------------------------------------------------------
    """
    def createCipher(self):
        if self.algo_type == 'aes':
            self.cipher = AesCipher(self.keysize,
                                    self.plaintext_file_path,
                                    self.ciphertext_file_path,
                                    self.init_vector,
                                    self.key)
        elif self.algo_type == '3es':
            print('3es')
        elif self.algo_type == 'des':
            print('des')

    """
    --------------------------------------------------------------------------------------------------------------------
    Setup the monitor class and move to its own thread
    --------------------------------------------------------------------------------------------------------------------
    """
    def setupMonitor(self):
        self.monitor_progress_thread = QThread()
        self.progress_monitor = ProgressMonitor(self.percent_done,
                                               self.paused,
                                               self.pause_sig_sent,
                                               self.end_process_early)
        self.progress_monitor.moveToThread(self.monitor_progress_thread)
        # connect signals and slots
        self.monitor_progress_thread.started.connect(self.progress_monitor.beginMonitoring)
        self.progress_monitor.updateProcessSig.connect(self.update)
        self.progress_monitor.endProcessEarlySig.connect(self.endEarly)
        self.progress_monitor.endProcessSig.connect(self.complete)
        self.progress_monitor.pauseSig.connect(self.showCancelMessage)

    """
    --------------------------------------------------------------------------------------------------------------------
    Create the Cipher Process and set the target to the appropriate method in the Cipher instance
    --------------------------------------------------------------------------------------------------------------------
    """
    def createCipherProcess(self):
        if self.mode == 'encryption':
            self.cipher_process = Process(target=self.cipher.encrypt, args=(self.percent_done,
                                                                            self.pause_requested,
                                                                            self.paused))
        elif self.mode == 'decryption':
            self.cipher_process = Process(target=self.cipher.decrypt, args=(self.percent_done,
                                                                            self.pause_requested,
                                                                            self.paused))

    """
    --------------------------------------------------------------------------------------------------------------------
    Begin the encryption/decryption process and start the monitoring thread
    --------------------------------------------------------------------------------------------------------------------
    """
    def begin(self):
        self.monitor_progress_thread.start()
        self.cipher_process.start()

    """
    --------------------------------------------------------------------------------------------------------------------
    Update the progress bar with values from the encryption/decryption process
开发者ID:fraserjohnstone,项目名称:File-Safe-Pure-Python-AES-Implementation,代码行数:70,代码来源:Progress.py

示例15: SyncWindow

# 需要导入模块: from PySide.QtCore import QThread [as 别名]
# 或者: from PySide.QtCore.QThread import start [as 别名]
class SyncWindow(QMainWindow):
    """
    Application main window. This class is meant to handle
    every widget needed by the application, as well as other
    needed global objects and behavior.
    """
    
    failedLogIn = Signal()
    syncStarted = Signal()
    loginRequested = Signal((str, str,))
    statusChanged = Signal((str, str, int,))
    
    def __init__(self, parent=None):
        super(SyncWindow, self).__init__(parent)
        
        # Sets up several UI aspects
        self.tray = QSystemTrayIcon(self)
        self.tray.setIcon(QIcon(QPixmap(':/resources/icon.png')))
        self.tray.show()
        
        self.setStyleSheet('SyncWindow {background: white}')
        self.setWindowTitle('IQBox')
        self.setWindowIcon(QIcon(QPixmap(':/resources/logobar.png')))
        self.statusBar().setFont(View.labelsFont())
        self.syncThread = None
        
        # Initializes the window with a `LoginView` widget.
        self.loginView()
        
    def loginView(self):
        """
        Initializes a `LoginView` object and sets it up as the main window's
        central widget.
        """
        login = LoginView()
        
        login.login.connect(self.onLogin)
        self.failedLogIn.connect(login.onFailedLogIn)
        
        self.setCentralWidget(login)
        self.setFixedSize(login.size())
        self.statusBar().hide()
        
    def syncView(self):
        """
        Initializes a `SyncView` object and sets it up as the main window's
        central widget.
        """        
        
        syncview = SyncView()
        
        self.setCentralWidget(syncview)
        self.setFixedSize(syncview.size())
        self.statusBar().show()
       
        self.statusChanged.connect(syncview.status.setMessage)
        syncview.sync.connect(self.onSync)
        
    @Slot(str, str, str, bool)
    def onLogin(self, host, username, passwd, ssl):
        """
        Slot. Triggers a log in request to the server.
        
        :param host: Indicates the hostname of the FTP server
        :param username: Username to log in into the FTP server
        :param passwd: Password to log in into the FTP server
        :param ssl: Indicates whether the FTP needs SSL support
        """

        self.sync = Sync(host, ssl)
        self.syncStarted.connect(self.sync.initQueue)
        self.sync.server.downloadProgress.connect(self.onDownloadProgress)
        self.sync.server.uploadProgress.connect(self.onUploadProgress)
        self.sync.server.fileEvent.connect(self.onFileEvent)
        self.sync.server.badFilenameFound.connect(self.badNameWarning)
        self.sync.server.loginCompleted.connect(self.onLoginCompleted)
        self.sync.server.fileEventCompleted.connect(self.onFileEventCompleted)
        self.sync.server.ioError.connect(self.onIOError)
        # Added by Si
        self.sync.server.textStatus.connect(self.setStatus)
        
        self.sync.statusChanged.connect(self.setStatus)
        self.loginRequested.connect(self.sync.server.onLogin) 

        self.syncThread = QThread()
        self.sync.moveToThread(self.syncThread)
        self.syncThread.start()
    
        QApplication.instance().lastWindowClosed.connect(self.syncThread.quit)
        self.loginRequested.emit(username, passwd)

    @Slot(bool, str)
    def onLoginCompleted(self, ok, msg):
        if not ok:
            self.showMessageBox(msg)
            self.failedLogIn.emit()

        else:
            self.syncView()
                
#.........这里部分代码省略.........
开发者ID:ShareByLink,项目名称:iqbox-ftp,代码行数:103,代码来源:window.py


注:本文中的PySide.QtCore.QThread.start方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。