Пример #1
0
 def run(self):
     try:
         self.handle = ctypes.windll.kernel32.OpenThread(  # @UndefinedVariable
             win32con.PROCESS_ALL_ACCESS, False, int(QThread.currentThreadId()))
     except Exception as e:
         print('get thread handle failed', e)
     print('thread id', int(QThread.currentThreadId()))
     for i in range(1, 101):
         print('value', i)
         self.valueChanged.emit(i)
         QThread.sleep(1)
Пример #2
0
    def __init__(self, email, password, proccess_id, parent=None):

        super().__init__()
        try:
            print('TrueCaller: ', int(QThread.currentThreadId()))
            self.email = email
            self.password = password
            self.proccess_id = proccess_id

            # save cookies for preventing repetitive login from one client
            cookies_dir = BASE_APP_PATH + "/modules/truecaller/v_1_0/cookies/"
            cookie_hashname = str(hashlib.md5(self.email.encode('utf-8')).hexdigest()) + str(
                hashlib.md5(self.password.encode('utf-8')).hexdigest()) + '.pkl'
            self.cookie_path = cookies_dir + cookie_hashname
            os.makedirs(cookies_dir, exist_ok=True)

            # profile name
            # profile_name = str(hashlib.md5(self.email.encode('utf-8')).hexdigest()) + str(hashlib.md5(self.password.encode('utf-8')).hexdigest())
            # self.robot = Hrobot(gui=True, private=True, profile_name=profile_name)

            self.robot = Hrobot(gui=True, private=True)
            print('before')

            self.set_cookie(self.cookie_path)

            self.robot.go_to("https://www.truecaller.com")
            print('after ')

        except Exception as e:  # can not go to mbasic.facebook.com
            raise NetworkError(str(e))
Пример #3
0
 def __init__(self):
     super().__init__()
     # 【1】THREAD 声明
     self._thread = QThread()  # 声明:声明一个实例
     self.moveToThread(self._thread)  # 声明2:把自己这个类移动到这个新线程里
     self._thread.started.connect(self.working)  # 多线程只能链接一个函数
     print('Main_Thread_ID={}'.format(int(QThread.currentThreadId())))
    def run(self, item):
        print("From workThread: ", QThread.currentThreadId())
        detector = Detector()
        detected = item.data(1, Qt.UserRole)[0]
        if detected:
            return
        dcmFileName = item.data(0, Qt.UserRole)
        result = detector.detect(dcmFileName)
        result.insert(0, True)

        classes = result[3]
        brush = QBrush(Qt.SolidPattern)
        if 5.0 in classes:
            item.setText(1, "骨质异常")
            brush.setColor(Qt.GlobalColor.cyan)
        elif 3.0 in classes or 4.0 in classes:
            item.setText(1, "骨折")
            brush.setColor(Qt.GlobalColor.red)
        elif 6.0 in classes:
            item.setText(1, "发育异变")
            brush.setColor(Qt.GlobalColor.yellow)
        else:
            item.setText(1, "正常")
            brush.setColor(Qt.GlobalColor.white)
        item.setBackground(1, brush)
        item.setTextAlignment(1, Qt.AlignCenter)
        item.setData(1, Qt.UserRole, result)

        self.gotThisResult.emit()
    def on_actOpen_triggered(self):
        ##返回的文件夹路径
        path = QFileDialog.getExistingDirectory()
        if (path == ""):
            return

        ##生成进度条组件
        self.numTotal = len([
            lists for lists in os.listdir(path)
            if os.path.isfile(os.path.join(path, lists))
        ])  ##文件总数
        self.numLoad = 0  ##已加载数
        self.lab1.setText(" 加载中")
        self.prg.setRange(0, self.numTotal)
        self.prg.setValue(0)
        self.lab2.setText(" 剩余文件:" + str(self.numTotal - self.numLoad))
        self.actLab1.setVisible(True)
        self.actPrg.setVisible(True)
        self.actLab2.setVisible(True)

        print("From mainThread: ", QThread.currentThreadId())

        ##建立工作线程
        workThread = QThread(parent=self)

        openDir = OpenDir(path, self.itemFlags)
        openDir.moveToThread(workThread)
        openDir.dirError.connect(self.do_dirError)
        openDir.newDcmFile.connect(self.do_newDcmFile)
        openDir.openFinished.connect(self.do_openFinished)
        openDir.openFinished.connect(workThread.quit)
        workThread.started.connect(lambda: openDir.run(self.ui.treeFiles))

        workThread.start()
Пример #6
0
 def showTable(self):
     print('showTable', int(QThread.currentThreadId()))
     self.progressBar.setMaximum(self.table_row)
     self.plainTextEdit.appendPlainText(
         datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') + ' 加载中...')
     for row in range(self.table_row):
         for column in range(self.table_column):
             content = self.table_content[row][column]
             if isinstance(self.table_content[row][column],
                           datetime.datetime):
                 content = self.table_content[row][column].strftime(
                     '%Y/%m/%d')
             if content is not None:
                 content = str(content)
             table_item = QtWidgets.QTableWidgetItem(content)
             self.tableWidget.setItem(row, column, table_item)
         self.progressBar.setValue(row + 1)
         self.label_3.setText(str(row + 1) + '/' + str(self.table_row))
     #self.sleep(0.5)
     #self.quit()
     self.lineEdit.setText(str(self.table_row))
     self.plainTextEdit.appendPlainText(
         datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') + ' 加载完成')
     self.label_3.setText('加载完成')
     self.label_4.hide()
Пример #7
0
    def run(self):
        # 实例化一个读取视频对象
        cap = cv2.VideoCapture(self.video_name)

        while cap.isOpened():
            # 读取视频帧
            ret, frame = cap.read()
            # 获取视频的帧数
            fps = cap.get(cv2.CAP_PROP_FPS)

            if ret:
                # 转换图片格式
                rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                qt_image = QImage(rgb_image.data, rgb_image.shape[1],
                                  rgb_image.shape[0], QImage.Format_RGB888)
                p = qt_image.scaled(640, 480, Qt.KeepAspectRatio)
                # 发射信号
                print('线程: %s' % hex(int(QThread.currentThreadId())))
                self.show_signal.emit(p)
                time.sleep(1 / fps)
            else:
                image = QImage('E:/11.jpg')
                self.browser.ui.lb_show.setPixmap(QPixmap.fromImage(image))
                self.browser.ui.lb_show.adjustSize()
                print('播放结束')
                break
Пример #8
0
def piteca_excepthook(exctype, value, tb):
    """
    A method to catch all unhandled exception during PITECA's run .
    :param exctype: the type of exception
    :param value: the message of the exception (use str(value))
    :param tb: traceback
    """

    # if not gb.should_exit_on_error:
    # # If we are on main thread but don't want to close PITECA
    #     dialog_utils.print_error(constants.UNEXPECTED_EXCEPTION_MSG[:-1] + ": " + str(value))
    #     return

    # Show user the full error value only if it is a PITECA error
    if exctype == definitions.PitecaError:
        msg = str(value.message)
    else:
        msg = constants.UNEXPECTED_EXCEPTION_MSG

    if int(QThread.currentThreadId()) == main_thread_id:
        definitions.print_in_debug(value)
        traceback.print_tb(tb)
        dialog_utils.print_error(msg + ". PITECA will be now closed")
        sys.exit()
    else:
        # The exception_occurred_sig should be defined in every thread class in PITECA
        definitions.print_in_debug(value)
        definitions.print_in_debug(exctype)
        traceback.print_tb(tb)
        QThread.currentThread().exception_occurred_sig.emit(msg)
Пример #9
0
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(self)
        self.progressBar = QProgressBar(self)
        self.progressBar.setRange(0, 100)
        layout.addWidget(self.progressBar)
        self.startButton = QPushButton('开启线程', self, clicked=self.onStart)
        layout.addWidget(self.startButton)
        self.suspendButton = QPushButton('挂起线程',
                                         self,
                                         clicked=self.onSuspendThread,
                                         enabled=False)
        layout.addWidget(self.suspendButton)
        self.resumeButton = QPushButton('恢复线程',
                                        self,
                                        clicked=self.onResumeThread,
                                        enabled=False)
        layout.addWidget(self.resumeButton)
        self.stopButton = QPushButton('终止线程',
                                      self,
                                      clicked=self.onStopThread,
                                      enabled=False)
        layout.addWidget(self.stopButton)

        # 当前线程id
        print('main id', int(QThread.currentThreadId()))

        # 子线程
        self._thread = Worker(self)
        self._thread.finished.connect(self._thread.deleteLater)
        self._thread.valueChanged.connect(self.progressBar.setValue)
Пример #10
0
    def work(self):
        """
        Pretend this worker method does work that takes a long time. During this time, the thread's
        event loop is blocked, except if the application's processEvents() is called: this gives every
        thread (incl. main) a chance to process events, which in this sample means processing signals
        received from GUI (such as abort).
        """
        thread_name = QThread.currentThread().objectName()
        thread_id = int(
            QThread.currentThreadId())  # cast to int() is necessary
        self.sig_msg.emit('Running worker #{} from thread "{}" (#{})'.format(
            self.__id, thread_name, thread_id))

        for step in range(100):
            time.sleep(0.1)
            self.sig_step.emit(self.__id, 'step ' + str(step))

            # check if we need to abort the loop; need to process events to receive signals;
            # app.processEvents()  # this could cause change to self.__abort
            if self.__abort:
                # note that "step" value will not necessarily be same for every thread
                self.sig_msg.emit('Worker #{} aborting work at step {}'.format(
                    self.__id, step))
                break

        self.sig_done.emit(self.__id)
Пример #11
0
def _main_thread():
    app = QApplication.instance()
    if app:
        return app.thread()
    # We reach here in tests that don't (want to) create a QApplication.
    if int(QThread.currentThreadId()) == get_ident():
        return QThread.currentThread()
    raise RuntimeError('Could not determine main thread')
Пример #12
0
 def working(self):  # 只在这个函数块里面的有可能是在多线程
     num = 0
     while 1:
         num += 1
         print('Child_Thread_ID={}'.format(int(QThread.currentThreadId())),
               num)
         time.sleep(1)
         self.sign_output.emit(num)
Пример #13
0
 def run(self):
     print('thread id', int(QThread.currentThreadId()))
     i = 0
     while i < 101 and not self.isInterruptionRequested():
         print('value', i, time())
         i += 1
         QThread.msleep(500)
     print('thread quit')
Пример #14
0
    def __init__(self, context, signals):
        super(StatusThread, self).__init__()
        """
        QThread which processes data and hands it to the main thread.

        After checking whether the current mode is either calibrating or
        running, values are obtained from the ValueReader. Dictionaries for
        buffers, buffer averages, and notable events for the initial intensity,
        diffraction intensity, and the ratio of these is built.

        parameters:
        ----------
        signals : object
        context : object
        """

        self.signals = signals
        self.context = context
        self.calibration_source = ''
        self.flag_message = None
        self.refresh_rate = 0
        self.display_time = 0
        self.buffer_size = 0
        self.percent = 1
        self.averaging_size = 0
        self.notification_tolerance = 0
        self.graph_ave_time = 0
        self.count = 0
        self.naverage = 0
        self.ave_cycle = []
        self.ave_idx = []
        self.x_cycle = []
        self.x_axis = []
        self.calibrated = False
        self.isTracking = False
        self.badScanCounter = 0
        self.badScanLimit = 2
        self.mode = ''
        self.status = ''
        self.display_flag = []
        self.cal_vals = [[], [], []]
        self.calibration_values = {'i0': {'mean': 0, 'stddev': 0,
                                          'range': (0, 0)},
                                   'diff': {'mean': 0, 'stddev': 0,
                                            'range': (0, 0)},
                                   'ratio': {'mean': 0, 'stddev': 0,
                                             'range': (0, 0)}}
        self.averages = {}
        self.buffers = {}
        self.current_values = {}
        self.flagged_events = {}
        self.create_value_reader()
        self.create_event_processor()
        self.create_vars()
        self.connect_signals()
        self.initialize_buffers()

        log.info("__init__ of StatusThread: %d" % QThread.currentThreadId())
Пример #15
0
 def __init__(self):  #,  parent=None
     pass
     # super(CRT, self).__init__(parent)
     print('%-25s: %s, %s,' %
           ("scriptCRTfunc_init", QThread.currentThread(),
            int(QThread.currentThreadId())))
     print('%-25s: %s, %s,' %
           ("scriptCRTfunc_init", threading.current_thread().name,
            threading.current_thread().ident))
Пример #16
0
    def long_running(self):
        print('SomeObject(QObject) id', int(QThread.currentThreadId()))
        count = 0
        while count < 150:
            Qt.QThread.msleep(100)
            count += 1
            self.threadSignalSomeObject.emit(count)

        self.finishedSomeObject.emit()
 def on_str(self, data: str) -> None:
     if VERBOSE:
         print("on_str received: {} [thread {}]".format(
             repr(data), int(QThread.currentThreadId())))
     if ((WITH_TEMPORARY_VARIABLES and
             data not in SOURCE_STR_FOR_TEMP.split(" ")) or
             (not WITH_TEMPORARY_VARIABLES and
                 data not in SOURCE_STR_STATIC)):
         print("FAILURE: on_str received {}".format(repr(data)))
    def initialize(self):

        self.issue_encountered.connect(self.close)
        # First, make sure when any issue is encountered, go cleanup.

        print("Starting Serial Data Listener")
        print("Worker Thread ID:", int(QThread.currentThreadId()))

        self.num_frame_shifts = 0
        self.frame_suceess = True
        self.timer = QTimer(self)

        data_root = 'CANRGX_data\\' + time.strftime('%Y_%m_%d_%H_%M_%S') + '\\'
        if not os.path.exists(data_root):
            os.makedirs(data_root)

        self.file = open(
            data_root + time.strftime('%Y_%m_%d_%H_%M_%S') + ".txt", 'w')
        self.logString("Log created at " + str(os.getcwd()) + '\\' + data_root)
        self.canrgx_log = canrgx_log_files(data_root)

        self.ser = serial.Serial(self.ser_port, 230400, timeout=100)
        time.sleep(0.100)  # A 100 ms delay typically can help with some serial
        # port issues
        self.logString("Opened port " + self.ser.name)
        # Wait for microcontroller to come on and send its startup message
        self.ser.reset_output_buffer()
        self.ser.reset_input_buffer()
        try:
            self.printAndLogStringFromSerial("MCU sent: ")
        except UnicodeDecodeError as decode_err:
            print('Not valid MCU response, quit')
            return
        self.sendToMCU('A')  # ACK

        # Wait for microcontroller to send its MPU9250 initialization status
        self.printAndLogStringFromSerial("MCU sent: ")
        self.sendToMCU('A')  # ACK

        # Write current time to microcontroller and wait for it to send the
        # time back after a short delay. Log this time, as it is the time
        # the microcontroller is starting the scheduler.
        # One experiment showed there is a (310434-309425)/2 = 504.5
        # microsecond delay when sending the time. This may vary a bit, and
        # so should ideally be done on-the-fly.
        self.sendToMCU(datetime.now().strftime('%H.%M.%S.%f'))
        self.printAndLogStringFromSerial("MCU starting scheduler. Echoed: ")
        self.sendToMCU('A')

        self.timer.timeout.connect(self.check_serial_buffer)
        # Create the timer that fires every 2ms to check the serial buffer.
        self.initialized.emit()

        print("Start Listening to MCU Data")

        self.timer.start(2)
Пример #19
0
 def __init__(self, context, signals):
     super(ControlsWidget, self).__init__()
     log.info("Main Thread: %d" % QThread.currentThreadId())
     self.signals = signals
     self.context = context
     self.setupUi(self)
     self.initialize_threads()
     self.set_thread_options()
     self.set_motor_options()
     self.make_connections()
Пример #20
0
 def __init__(self, delay, parent=None):
     super().__init__(None)
     self.delay = delay
     self.threadName = QThread.currentThread().objectName()
     print("Initializing new thread with delay {}".format(self.delay))
     print("Thread with delay {} is named: {}".format(
         self.delay, self.threadName))
     self.threadId = int(QThread.currentThreadId())
     print("Thread with delay {} has an ID: {}".format(
         self.delay, self.threadId))
Пример #21
0
    def run(self):
        print("t2:" + str(QThread.currentThreadId()))
        #timer.start(1000)
#        print(timer.remainingTime())
#        print(timer.isActive())
        
        self.timer2 = QtCore.QTimer()
        self.timer2.start(1000)
        self.timer2.timeout.connect(self.tick)
        self.exec_()
Пример #22
0
    def run(self):
        print("t2:" + str(QThread.currentThreadId()))
        #timer.start(1000)
        #        print(timer.remainingTime())
        #        print(timer.isActive())

        self.timer2 = QtCore.QTimer()
        self.timer2.start(1000)
        self.timer2.timeout.connect(self.tick)
        self.exec_()
Пример #23
0
    def work(self):
        """
        Pretend this worker method does work that takes a long time. During this time, the thread's
        event loop is blocked, except if the application's processEvents() is called: this gives every
        thread (incl. main) a chance to process events, which in this sample means processing signals
        received from GUI (such as abort).
        """
        thread_name = QThread.currentThread().objectName()
        thread_id = int(
            QThread.currentThreadId())  # cast to int() is necessary
        self.sig_msg.emit(
            'Executando tarefa #{} da thread "{}" start:{} stop:{} (#{})'.
            format(self.__id, thread_name, self.start, self.finish, thread_id))

        try:

            if int(self.start) == int(self.finish):
                request = SLICE_REQUEST + str(self.start) + ":" + str(
                    self.finish) + ":" + self.filename
                self.s.sendto(request.encode(), self.server_address)
                data, addr = self.s.recvfrom(BUFFER_SIZE)
            else:
                request = SLICE_REQUEST + str(self.start) + ":" + str(
                    self.finish) + ":" + self.filename
                self.s.sendto(request.encode(), self.server_address)
                data, addr = self.s.recvfrom(BUFFER_SIZE)

                while data:
                    self.s.settimeout(2)  # set time out

                    header = (data[:LEN_HEADER].decode())  # header packet
                    id, time_send = header.strip().split(':')
                    packet_id = int(id)

                    self.sig_get_packet.emit(packet_id, time_send,
                                             data[LEN_HEADER:])

                    data, addr = self.s.recvfrom(BUFFER_SIZE)

                    # check if we need to abort the loop; need to process events to receive signals;
                    QApplication.processEvents(
                    )  # this could cause change to self.__abort
                    if self.__abort:
                        # note that "packet_id" value will not necessarily be same for every thread
                        self.sig_msg.emit(
                            'Tarefa #{} abortada no pacote {}'.format(
                                self.__id, packet_id))
                        break

        except Exception as e:
            print(e)

        self.sig_done.emit(self.__id)
        self.s.close()
Пример #24
0
    def doConversion(self):
        """
        Performs the conversion from DICOM to PNG, applying any LUT that is embedded.
        """
        thread_id = int(QThread.currentThreadId())  # cast to int() is necessary
        error_flag = False
        # thread_name = QThread.currentThread().objectName()
        # print("Worker: id {}  name {}".format(thread_id, thread_name))

        info = self.task_info
        file_path = info["file_path"]
        output_path = info["output_path"]
        basename = info["basename"]
        self.sig_msg.emit('Starting conversion for "{}"'.format(basename, thread_id))
        try:
            self.checkPoint(info, "[0]")
            img, hdr = read_dicom(file_path)
            self.checkPoint(info, "[1]")

            if not os.path.isdir(output_path):
                os.makedirs(output_path)

            # Make a unique filename based on the DICOM header info:
            output_file = generate_unique_filename(hdr, ".png")
            output_file = os.path.join(output_path, output_file)

            self.checkPoint(info, "[2]")

            # Convert to greyscale in range 0-255
            img = img.astype(float)
            img -= img.min()
            img /= img.max()
            img *= 255.0

            # Convert to 8-bit unsigned int:
            img = img.astype("uint8")
            shape = img.shape

            self.checkPoint(info, "[3]")

            # Write in PNG format:
            writer = png.Writer(shape[1], shape[0], greyscale=True)
            with open(output_file, "wb") as fout:
                writer.write(fout, img)
            self.sig_msg.emit('[OK]: Finished converting "{}"'.format(basename))
        except self.AbortConversion as e:
            self.sig_msg.emit("[FAIL]: {}".format(str(e)))
            error_flag = True
        except Exception as e:
            self.sig_msg.emit('[FAIL]: Failed converting "{}" ({})'.format(basename, e))
            error_flag = True

        self.sig_done.emit(self.id, error_flag)
Пример #25
0
    def sendimg(self, img_queue):

        img_sock = self.img_sock
        img_address = self.img_address
        running = True
        cnt = 0
        img_sock.connect(img_address)
        qDebug('sendimg Worker.on_timeout get called from: %s' %
               hex(int(QThread.currentThreadId())))
        while running:
            frame = img_queue.get()
            img_sock.sendto(frame, img_address)
Пример #26
0
 def checkPoint(self, info, msg=None):
     """
     See if work can continue; raises an AbortConversion exception if we need to stop.
     """
     msg_suffix = ""
     thread_id = int(QThread.currentThreadId())
     if msg is not None:
         msg_suffix = ": {}".format(msg)
     msg = 'Conversion cancelled "{}" {}'.format(info["basename"], msg_suffix)
     # check if we need to abort the loop; need to process events to receive signals;
     app.processEvents()  # this could cause change to self.abort
     if self.abort_requested:
         raise self.AbortConversion(msg)
Пример #27
0
  def run(self):
    ''' Demarre la communication avec le port serie dans un thread separe '''

    thread_name = QThread.currentThread().objectName()
    thread_id = int(QThread.currentThreadId())  # cast to int() is necessary
    self.sig_log.emit(logSeverity.info.value, self.tr('grblComSerial.run(): Running "{}" from thread #{}.').format(thread_name, hex(thread_id)))

    if self.__openComPort():
      self.__mainLoop()
    else:
      self.sig_log.emit(logSeverity.error.value, self.tr("grblComSerial.run(): Unable to open serial port!"))
      # Emission du signal de fin
      self.sig_log.emit(logSeverity.info.value, self.tr("grblComSerial.run(): End."))
Пример #28
0
    def work(self):
        """
        Pretend this worker method does work that takes a long time. During this time, the thread's
        event loop is blocked, except if the application's processEvents() is called: this gives every
        thread (incl. main) a chance to process events, which in this sample means processing signals
        received from GUI (such as abort).
        """
        thread_name = QThread.currentThread().objectName()
        thread_id = int(
            QThread.currentThreadId())  # cast to int() is necessary
        self.sig_msg.emit('Running worker #{} from thread "{}" (#{})'.format(
            self.__id, thread_name, thread_id))

        # Creates a new connection to DeepGTAV using the specified ip and port.
        # If desired, a dataset path and compression level can be set to store in memory all the data received in a gziped pickle file.
        # We don't want to save a dataset in this case
        self.client = Client(ip=self.args.host, port=self.args.port)
        # self.client = Client(ip="127.0.0.1", port=8000)

        # We set the scenario to be in manual driving, and everything else random (time, weather and location).
        # See deepgtav/messages.py to see what options are supported
        scenario = Scenario(drivingMode=-1)  #manual driving

        # Send the Start request to DeepGTAV. Dataset is set as default, we only receive frames at 10Hz (320, 160)
        self.client.sendMessage(Start(scenario=scenario))

        # Dummy agent
        model = Model()

        # Start listening for messages coming from DeepGTAV. We do it for 80 hours
        stoptime = time.time() + 80 * 3600
        while (time.time() < stoptime and (not self.__abort)):
            # We receive a message as a Python dictionary
            app.processEvents()
            message = self.client.recvMessage()

            # The frame is a numpy array that can we pass through a CNN for example
            image = frame2numpy(message['frame'], (320, 160))
            commands = model.run(image)
            self.sig_step.emit(self.__id, 'step ' + str(time.time()))
            self.sig_image.emit(image.tolist())
            # We send the commands predicted by the agent back to DeepGTAV to control the vehicle
            self.client.sendMessage(
                Commands(commands[0], commands[1], commands[2]))

        # We tell DeepGTAV to stop
        self.client.sendMessage(Stop())
        self.client.close()

        self.sig_done.emit(self.__id)
Пример #29
0
 def run(self):
     global SESSION_DATA,EXIT_COND
     try:
         self.handle = ctypes.windll.kernel32.OpenThread(  # @UndefinedVariable
             win32con.PROCESS_ALL_ACCESS, False, int(QThread.currentThreadId()))
     except Exception as e:
         print('get thread handle failed', e)
     # print('thread id', int(QThread.currentThreadId()))
     # 循环发送信号
     while True:
         if SESSION_DATA:
             self.valueChanged.emit(1024)
             SESSION_DATA = False
         time.sleep(0.1)
Пример #30
0
 def run(self):
     '''任务进度条'''
     try:
         self.handle =ctypes.windll.kernel32.OpenThread(
         win32con.PROCESS_ALL_ACCESS, False, int(QThread.currentThreadId()))
     except Exception as e:
         pass
     else:
         with tqdm(total=self.num) as bar:
             for i in range(self.num):
                 # print(i)
                 bar.update(1)
                 self.signal.emit(1)
                 time.sleep(1)
Пример #31
0
    def __init__(self, *args, **kwargs):
        super(Window, self).__init__(*args, **kwargs)
        layout = QVBoxLayout(self)
        self.progressBar = QProgressBar(self)
        self.progressBar.setRange(0, 100)
        layout.addWidget(self.progressBar)
        layout.addWidget(QPushButton('开启线程', self, clicked=self.onStart))

        # 当前线程id
        print('main id', int(QThread.currentThreadId()))

        # 子线程
        self._thread = Worker(self)
        self._thread.finished.connect(self._thread.deleteLater)
        self._thread.valueChanged.connect(self.progressBar.setValue)
Пример #32
0
        self.timer2.start(1000)
        self.timer2.timeout.connect(self.tick)
        self.exec_()

    def tick(self):
        #PyQt5.QtCore.QMetaObject.invokeMethod
        r=PyQt5.QtCore.Q_RETURN_ARG(int)
        print("timer 2 tick:" + str(QThread.currentThreadId()))
        self.metaObject().invokeMethod(rec, 'rec', PyQt5.QtCore.Qt.BlockingQueuedConnection, r)
        #self.my_signal.emit(lambda a,b: print("timer 2 lambda ran in:" + str(QThread.currentThreadId())))


#timer = QtCore.QTimer()
#timer.timeout.connect(timer_func)


#print(QThread.currentThread())
print(QThread.currentThreadId())


def t2h(l):
    print("t2h:" + str(QThread.currentThreadId()))
    l(1,2)


app = QtWidgets.QApplication(sys.argv)
thread_instance = Thread()
#thread_instance.my_signal.connect(t2h, Qt)
thread_instance.start()
sys.exit(app.exec_())
Пример #33
0
def t2h(l):
    print("t2h:" + str(QThread.currentThreadId()))
    l(1,2)
Пример #34
0
 def tick(self):
     #PyQt5.QtCore.QMetaObject.invokeMethod
     r=PyQt5.QtCore.Q_RETURN_ARG(int)
     print("timer 2 tick:" + str(QThread.currentThreadId()))
     self.metaObject().invokeMethod(rec, 'rec', PyQt5.QtCore.Qt.BlockingQueuedConnection, r)