예제 #1
0
    def testSlowJobs(self):
       for i in range(3):
           task = Task()
           QThreadPool.globalInstance().start(task)
           time.sleep(1) # Sleep 1 second

       QThreadPool.globalInstance().waitForDone()
예제 #2
0
    def __init__(self):
        super().__init__()

        # Some buttons
        layout = QVBoxLayout()

        self.name = QLineEdit()
        layout.addWidget(self.name)

        self.country = QLineEdit()
        layout.addWidget(self.country)

        self.website = QLineEdit()
        layout.addWidget(self.website)

        self.number_of_lines = QSpinBox()
        layout.addWidget(self.number_of_lines)

        btn_run = QPushButton("Execute")
        btn_run.clicked.connect(self.start)

        layout.addWidget(btn_run)

        w = QWidget()
        w.setLayout(layout)
        self.setCentralWidget(w)

        # Thread runner
        self.threadpool = QThreadPool()

        self.show()
예제 #3
0
파일: api.py 프로젝트: schoentoon/runekit
 def __init__(self, api: Alt1Api, rpc_secret: bytes, parent=None):
     super().__init__(parent)
     self.api = api
     self.rpc_secret = rpc_secret
     self.logger = logging.getLogger(__name__ + "." +
                                     self.__class__.__name__)
     self.thread_pool = QThreadPool(parent=self)
예제 #4
0
파일: bug_927.py 프로젝트: zhoub/pyside2
    def testSlowJobs(self):
        for i in range(3):
            task = Task()
            QThreadPool.globalInstance().start(task)
            time.sleep(1)  # Sleep 1 second

        QThreadPool.globalInstance().waitForDone()
예제 #5
0
    def __init__(self):
        super().__init__()

        self.counter = 0

        layout = QVBoxLayout()

        self.l = QLabel("Start")
        b = QPushButton("DANGER!")
        b.pressed.connect(self.oh_no)

        layout.addWidget(self.l)
        layout.addWidget(b)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" %
              self.threadpool.maxThreadCount())

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()
예제 #6
0
    def __init__(self, parent: QWidget, network: str = 'mainnet'):
        super().__init__()

        self.timer = QTimer(self.parentWidget())

        self.node_set = NodeSet(network)

        columns = 2

        layout = QGridLayout()
        self.nodes_layout = NodesLayout(node_set=self.node_set)
        layout.addLayout(self.nodes_layout, column_span=columns)

        self.lnd_wallet_layout = LndWalletLayout(node_set=self.node_set,
                                                 parent=parent)
        layout.addLayout(self.lnd_wallet_layout, column_span=columns)

        self.zap_layout = ZapLayout(node_set=self.node_set)
        layout.addLayout(self.zap_layout, column_span=columns)

        self.joule_layout = JouleLayout(node_set=self.node_set)
        layout.addLayout(self.joule_layout, column_span=columns)

        self.cli_layout = CliLayout(node_set=self.node_set)
        layout.addLayout(self.cli_layout, column_span=columns)

        self.setLayout(layout)

        self.threadpool = QThreadPool()

        self.timer.start(1000)
        self.timer.timeout.connect(self.refresh)

        self.refresh()
예제 #7
0
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        layout = QVBoxLayout()

        self.progress = QProgressBar()

        button = QPushButton("START IT UP")
        button.pressed.connect(self.execute)

        layout.addWidget(self.progress)
        layout.addWidget(button)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print(
            "Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()
        )

    def execute(self):
        worker = Worker()
        worker.signals.progress.connect(self.update_progress)

        # Execute
        self.threadpool.start(worker)

    def update_progress(self, progress):
        self.progress.setValue(progress)
예제 #8
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.setupUi(self)
     self.setStyleSheet(qss)
     self.config_widget = parent
     self.check_res = None
     self.btn_group = QButtonGroup(self)
     #
     self.res.setWordWrap(True)
     self.user.setFocus()
     self.host.textChanged.connect(self.host_slot)
     self.port.textChanged.connect(self.textChanged_slot)
     self.user.textChanged.connect(self.textChanged_slot)
     self.password.textChanged.connect(self.textChanged_slot)
     self.database.textChanged.connect(self.textChanged_slot)
     # 右键菜单
     self.ava_table.horizontalHeader().setVisible(False)
     self.ava_table.setContextMenuPolicy(
         Qt.CustomContextMenu)  ######允许右键产生子菜单
     self.ava_table.customContextMenuRequested.connect(
         self.generate_menu)  ####右键菜单
     # btn
     self.test_btn.clicked.connect(self.test_btn_slot)
     self.ok_btn.clicked.connect(self.ok_btn_slot)
     self.host.setText('localhost')
     self.port.setText('27017')
     self.url.setPlaceholderText(
         "mongodb://[user:password@]host:port/database")
     #
     self.thread_pool = QThreadPool()
     self.sig = DBObject()
     self.sig.dbsig.connect(self.db_connect_result)
def test_query(qtbot, conn):
    """Test asynchrone count query"""
    # Fill with a function that will be executed in a separated thread
    runnable = SqlRunnable(
        conn,
        function=sql.get_variants_count,
    )

    with qtbot.waitSignal(runnable.finished, timeout=10000) as blocker:
        QThreadPool.globalInstance().start(runnable)

    expected = 11
    assert expected == runnable.results

    # Same Query but via VQL wrapper
    runnable = SqlRunnable(
        conn,
        function=count_cmd,
    )

    with qtbot.waitSignal(runnable.finished, timeout=10000) as blocker:
        QThreadPool.globalInstance().start(runnable)

    expected = {"count": 11}
    assert expected == runnable.results
예제 #10
0
 def __init__(self, home, app_name=None):
     super(self.__class__, self).__init__()
     self.setupUi(self)
     self.setStyleSheet(qss)
     self.home = home
     self.interpreter = None
     self.p = QProcess()
     self.thread_pool = QThreadPool()
     # btn
     self.py_setting_btn.clicked.connect(self.py_setting_slot)
     self.set_app_py.clicked.connect(self.set_app_py_slot)
     #
     self.py_box.currentTextChanged.connect(self.py_change_slot)
     self.pip_list.setContextMenuPolicy(Qt.CustomContextMenu)
     self.pip_list.customContextMenuRequested.connect(self.generate_menu)  ####右键菜单
     #
     self.load_py()
     if not app_name:
         """用于设置窗口"""
         self.app_name.hide()
         self.set_app_py.hide()
         self.cur_py.hide()
         self.label_3.hide()
     else:
         """用于应用窗口"""
         self.app_name.setText(app_name)
         self.app_name.setStyleSheet("""color:#BE9117""")
         self.cur_py.setStyleSheet("""color:#168AD5""")
         path = G.config.installed_apps[app_name].get('py_', '未选择')
         for name, p in G.config.python_path.items():
             if path == p:
                 self.cur_py.setText(name)
             else:
                 self.cur_py.setText(path)
예제 #11
0
    def action_load_files(self):
        log.info("Loading .nif files ...")
        self.toggle(False)
        self.progress_bar.setMinimum(0)
        self.progress_bar.setMaximum(0)

        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.DirectoryOnly)
        file_dialog.setDirectory(self.source_folder)

        if file_dialog.exec_():
            scan_dirs = file_dialog.selectedFiles()
            if len(scan_dirs) >= 1:
                self.source_folder = scan_dirs[0]
            else:
                self.source_folder = file_dialog.directory()

        if self.source_folder:
            log.info("Scanning directory : " + self.source_folder)
            CONFIG.set("DEFAULT", "SourceFolder", self.source_folder),
            save_config()

        worker = Worker(self.load_files)
        worker.signals.progress.connect(self.update_nif_files)
        worker.signals.result.connect(self.finish_load_action)

        QThreadPool.globalInstance().start(worker)
예제 #12
0
    def __init__(self):
        super().__init__()

        self.threadpool = QThreadPool()

        self.totalTickets = QSpinBox()
        self.totalTickets.setRange(0, 500)
        self.serviceTickets = QSpinBox()
        self.serviceTickets.setRange(0, 250)
        self.incidentTickets = QSpinBox()
        self.incidentTickets.setRange(0, 250)
        self.unassignedTickets = QSpinBox()
        self.unassignedTickets.setRange(0, 200)
        self.reasonOne = QLineEdit()
        self.reasonTwo = QLineEdit()
        self.reasonThree = QLineEdit()
        self.additionalNotes = QTextEdit()

        self.generate_btn = QPushButton("Generate PDF")
        self.generate_btn.pressed.connect(self.generate)

        layout = QFormLayout()
        layout.addRow("Number of tickets today", self.totalTickets)
        layout.addRow("Service tickets", self.serviceTickets)
        layout.addRow("Incident tickets", self.incidentTickets)
        layout.addRow("Unassigned tickets", self.unassignedTickets)
        layout.addRow("Reason for most tickets", self.reasonOne)
        layout.addRow("Second reason for most tickets", self.reasonTwo)
        layout.addRow("Third reason for most tickets", self.reasonThree)

        layout.addRow("additionalNotes", self.additionalNotes)
        layout.addRow(self.generate_btn)

        self.setLayout(layout)
예제 #13
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.threadpool = QThreadPool()

        self.totalTickets = QSpinBox()
        self.totalTickets.setRange(0, 500)
        self.serviceTickets = QSpinBox()
        self.serviceTickets.setRange(0, 250)
        self.incidentTickets = QSpinBox()
        self.incidentTickets.setRange(0, 250)
        self.unassignedTickets = QSpinBox()
        self.unassignedTickets.setRange(0, 200)
        self.reasonOne = QLineEdit()
        self.reasonTwo = QLineEdit()
        self.reasonThree = QLineEdit()
        self.additionalNotes = QTextEdit()

        self.generate_btn = QPushButton("Generate PDF")
        self.generate_btn.pressed.connect(self.generate)

        layout = QFormLayout()
        layout.addRow("Number of tickets today", self.totalTickets)
        layout.addRow("Service tickets", self.serviceTickets)
        layout.addRow("Incident tickets", self.incidentTickets)
        layout.addRow("Unassigned tickets", self.unassignedTickets)
        layout.addRow("Reason for most tickets", self.reasonOne)
        layout.addRow("Second reason for most tickets", self.reasonTwo)
        layout.addRow("Third reason for most tickets", self.reasonThree)

        layout.addRow("additionalNotes", self.additionalNotes)
        layout.addRow(self.generate_btn)

        self.setLayout(layout)

    def generate(self):
        self.generate_btn.setDisabled(True)
        data = {
            'totalTickets': str(self.totalTickets.value()),
            'serviceTickets': str(self.serviceTickets.value()),
            'incidentTickets': str(self.incidentTickets.value()),
            'unassignedTickets': str(self.unassignedTickets.value()),
            'reasonOne': self.reasonOne.text(),
            'reasonTwo': self.reasonTwo.text(),
            'reasonThree': self.reasonThree.text(),
            'additionalNotes': self.additionalNotes.toPlainText()
        }
        g = Generator(data)
        g.signals.file_saved_as.connect(self.generated)
        g.signals.error.connect(print)  # Print errors to console.
        self.threadpool.start(g)

    def generated(self, outfile):
        self.generate_btn.setDisabled(False)
        try:
            os.startfile(outfile)
        except Exception:
            # If startfile not available, show dialog.
            QMessageBox.information(self, "Finished", "PDF has been generated")
예제 #14
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

        # Setting Column width
        header = self.oc_treeWidget.header()
        header.setSectionResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(False)
        header.setSectionResizeMode(7, QHeaderView.Stretch)

        self.oc_treeWidget.sortItems(0, Qt.AscendingOrder)

        self.actionFile.triggered.connect(self.fileButtonClicked)
        self.oc_treeWidget.currentItemChanged.connect(self.treeItemClicked)
        self.oc_treeWidget.itemClicked.connect(self.treeItemClicked)
        self.raw_checkBox.toggled.connect(self.highLightToggle)
        self.actionExit.triggered.connect(sys.exit)

        self.threadPool = QThreadPool()
        self.lastFile = ""

        self.statusbar.showMessage("Idle")
        self.fileLineCount = 0

        self.currentLineLoader = None
예제 #15
0
    def __init__(self):
        super(MovieLibrary, self).__init__()
        self.resize(800, 600)
        self.setWindowTitle("Movie Library")

        self.downloader_pool = QThreadPool()
        self.downloader_pool.setMaxThreadCount(8)

        # menu
        self.build_menu()

        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        main_layout = QHBoxLayout(central_widget)

        self.category_selector = CategorySelector()
        main_layout.addWidget(self.category_selector)

        self.movie_browser = MovieBrowser()
        main_layout.addWidget(self.movie_browser)

        self.apply_style()

        self.category_selector.filter_activated.connect(self.movie_browser.movie_list_view.do_filter)
예제 #16
0
 def __init__(self, mainwindow):
     super(self.__class__, self).__init__()
     self.setupUi(self)
     self.setStyleSheet(qss)
     self.mainwindow = mainwindow
     self.k_thread = QThreadPool()
     # calendar
     self.start.setCalendarPopup(True)
     self.end.setCalendarPopup(True)
     self.start.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
     self.end.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
     now = datetime.now() - timedelta(days=30)
     self.start.setDate(QDate(now.year, now.month, now.day))
     self.end.setDateTime(QDateTime.currentDateTime())
     #
     for local_symbol in sorted(G.all_contracts):
         self.symbol_list.addItem(local_symbol + contract_space + G.all_contracts[local_symbol])  # 添加下拉框
     self.symbol_list.currentIndexChanged.connect(self.symbol_change_slot)
     self.frq.addItems(['1min', '3min', '15min', '30min', '60min'])
     # table
     self.tick_table.setRowCount(0)
     self.tick_row = len(G.order_tick_row_map)
     self.tick_table.horizontalHeader().setStretchLastSection(True)  # 最后一列自适应表格宽度
     # self.tick_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自适应表格宽度
     self.tick_table.setEditTriggers(QTableWidget.NoEditTriggers)  # 单元格不可编辑
     self.tick_table.horizontalHeader().setVisible(False)  # 水平表头不可见
     self.tick_table.verticalHeader().setVisible(False)  # 垂直表头不可见
     # btn
     self.source_btn.clicked.connect(self.source_btn_slot)
     self.hide_btn.clicked.connect(self.hide_btn_slot)
     self.reload_btn.clicked.connect(self.k_line_reload)
     self.hide_btn_slot()  # 默认隐藏
     self.mainwindow.job.kline_tick_signal.connect(self.set_tick_slot)
     self.ready_action()
예제 #17
0
파일: zipvy.py 프로젝트: RamDurgaSai/zipvy
    def __init__(self):

        super(Zipvy, self).__init__()
        self.setupUi(self)
        self.show()

        # Load default Widgets Values
        # ....
        self.setWindowTitle("Zipvy - To Make Video from Zip")
        self.setWindowIcon(QIcon('images\\icon.ico'))
        self.terminal_output.setReadOnly(True)
        self.terminal_output.setPlainText("Zipvy is Ready....")
        self.progressBar.hide()
        self.label_progress.hide()
        self.same_as_zip_name_checkbox.setChecked(True)

        #Variables ....
        self.algorithm = 0
        self.zip_location = ""
        self.zip_name = ""
        self.lineEdit_text = ""
        self.video_name = ""
        self.video_location = ""

        #Threads...
        self.threadpool = QThreadPool()

        #Connect Signal to Slots...
        self.same_as_zip_name_checkbox.stateChanged.connect(
            self.checkbox_stat_changed)
        self.select_zip_button.clicked.connect(self.select_zip)
        self.start_button.clicked.connect(self.start)
        self.algorithm_combobox.currentIndexChanged.connect(self.set_algorithm)
        self.lineEdit.textChanged.connect(self.textedit_text_changed)
        self.toolButton.clicked.connect(self.set_video_location)
예제 #18
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Some buttons
        layout = QVBoxLayout()

        self.text = QPlainTextEdit()
        layout.addWidget(self.text)

        btn_run = QPushButton("Execute")
        btn_run.clicked.connect(self.start)

        layout.addWidget(btn_run)

        w = QWidget()
        w.setLayout(layout)
        self.setCentralWidget(w)

        # Thread runner
        self.threadpool = QThreadPool()

        self.show()

    def start(self):
        # Create a runner
        self.runner = SubProcessWorker("python dummy_script.py")
        self.runner.signals.result.connect(self.result)
        self.threadpool.start(self.runner)

    def result(self, s):
        self.text.appendPlainText(s)
예제 #19
0
    def __init__(self):
        QObject.__init__(self)
        self.__motor = ClearpathSCSK()
        self.__motor_nodes_count_list = [2]
        self.__motor_nodes_id_list = ["Disconnected 0", "Disconnected 1"]
        self.__motor_ports_connected = len(self.__motor_nodes_count_list)
        self.__building_plate_port = 0
        self.__wiper_port = 0
        self.__building_plate_node = 0
        self.__wiper_node = 1
        self.__wiper_recoat_offset_mm = 245
        self.__wiper_recoat_feedrate_mm_min = 1800
        self.__building_plate_recoat_offset_mm = 1
        self.__building_plate_recoat_feedrate_mm_min = 300
        self.__pause_toggle = False
        self.__ser = serial.Serial(timeout=5, write_timeout=0)
        self.__loaded_gcode = []
        self.__number_of_lines = 0
        self.__baudrates_list = (115200, 57600, 38400, 28800, 19200, 14400,
                                 9600, 4800, 2400, 1200, 600, 300)
        self.__baudrate = self.__baudrates_list[0]
        self.__com_port = ''
        self.__available_ports = serial.tools.list_ports.comports()
        ports = ()
        for p in self.__available_ports:
            ports = ports + (str(p.device), )
        self.__available_ports = ports
        if len(self.__available_ports) > 0:
            self.__com_port = self.__available_ports[0]

        self.__threadpool = QThreadPool()
예제 #20
0
    def __init__(self, node_set: NodeSet):
        super(LndWalletLayout, self).__init__()
        self.node_set = node_set
        self.password_dialog = QInputDialog()
        self.error_message = QErrorMessage()

        self.state = None

        self.threadpool = QThreadPool()

        columns = 2
        self.addWidget(SectionName('LND Wallet'), column_span=columns)
        wallet_buttons_layout = QtWidgets.QHBoxLayout()
        # Unlock wallet button
        self.unlock_wallet_button = QtWidgets.QPushButton('Unlock')
        # noinspection PyUnresolvedReferences
        self.unlock_wallet_button.clicked.connect(self.unlock_wallet)
        wallet_buttons_layout.addWidget(self.unlock_wallet_button)

        # Create wallet button
        self.create_wallet_button = QtWidgets.QPushButton('Create')
        # noinspection PyUnresolvedReferences
        self.create_wallet_button.clicked.connect(self.create_wallet)
        wallet_buttons_layout.addWidget(self.create_wallet_button,
                                        same_row=True,
                                        column=2)

        # Recover wallet button
        self.recover_wallet_button = QtWidgets.QPushButton('Recover')
        # noinspection PyUnresolvedReferences
        self.recover_wallet_button.clicked.connect(self.recover_wallet)
        wallet_buttons_layout.addWidget(self.recover_wallet_button)
        self.addLayout(wallet_buttons_layout, column_span=columns)

        self.addWidget(HorizontalLine(), column_span=columns)
예제 #21
0
 def computeStatistics(self, attribute: int) -> None:
     """ Compute statistics for a given attribute """
     flogging.appLogger.debug(
         'computeStatistics() called, attribute {:d}'.format(attribute))
     attType = self.__shape.colTypes[attribute]
     identifier = (attribute, attType, 'stat')
     if self.__frame.nRows == 0:
         return self.onWorkerError((attribute, attType, 'stat'), tuple())
     # Check if a task is already running for this attribute
     if self.existsRunningTask(identifier):
         return
     # Create a new task
     stats = AttributeStatistics()
     stats.setOptions(attribute=attribute)
     statWorker = Worker(stats,
                         args=(self.__frame, ),
                         identifier=identifier)
     rc = statWorker.signals.result.connect(self.onWorkerSuccess,
                                            Qt.DirectConnection)
     ec = statWorker.signals.error.connect(self.onWorkerError,
                                           Qt.DirectConnection)
     fc = statWorker.signals.finished.connect(self.onWorkerFinished,
                                              Qt.DirectConnection)
     flogging.appLogger.debug(
         'Connected stat worker: {:b}, {:b}, {:b}'.format(rc, ec, fc))
     # Remember which computations are already in progress
     self._runningWorkers.add(identifier)
     QThreadPool.globalInstance().start(statWorker)
예제 #22
0
파일: api.py 프로젝트: schoentoon/runekit
class RuneKitSchemeHandler(QWebEngineUrlSchemeHandler):
    api: Alt1Api

    def __init__(self, api: Alt1Api, rpc_secret: bytes, parent=None):
        super().__init__(parent)
        self.api = api
        self.rpc_secret = rpc_secret
        self.logger = logging.getLogger(__name__ + "." +
                                        self.__class__.__name__)
        self.thread_pool = QThreadPool(parent=self)

    def requestStarted(self, req: QWebEngineUrlRequestJob):
        headers = req.requestHeaders()
        token = headers.get(QByteArray(b"token"))
        if not secrets.compare_digest(token, self.rpc_secret):
            self.logger.warning("Invalid rpc secret: %s", repr(token))
            req.fail(QWebEngineUrlRequestJob.RequestDenied)
            return

        processor = RuneKitRequestProcess(self, req, parent=req)
        processor.signals.successSignal.connect(self.on_success)
        self.thread_pool.start(processor)

    @Slot(QWebEngineUrlRequestJob, bytes, bytes)
    def on_success(self, request, content_type, reply):
        body = QBuffer(parent=request)
        body.setData(reply)
        request.reply(content_type, body)
예제 #23
0
 def computeHistogram(self, attribute: int, histBins: int) -> None:
     flogging.appLogger.debug(
         'computeHistogram() called, attribute {:d}'.format(attribute))
     attType = self.__shape.colTypes[attribute]
     identifier = (attribute, attType, 'hist')
     if self.__frame.nRows == 0:
         return self.onWorkerError((attribute, attType, 'hist'), tuple())
     # Check if a task is already running for this attribute
     if self.existsRunningTask(identifier):
         return
     # Create a new task
     hist = Hist()
     hist.setOptions(attribute=attribute, attType=attType, bins=histBins)
     histWorker = Worker(hist, args=(self.__frame, ), identifier=identifier)
     rc = histWorker.signals.result.connect(self.onWorkerSuccess,
                                            Qt.DirectConnection)
     ec = histWorker.signals.error.connect(self.onWorkerError,
                                           Qt.DirectConnection)
     fc = histWorker.signals.finished.connect(self.onWorkerFinished,
                                              Qt.DirectConnection)
     flogging.appLogger.debug(
         'Connected hist worker: {:b}, {:b}, {:b}'.format(rc, ec, fc))
     # Remember computations in progress
     self._runningWorkers.add(identifier)
     QThreadPool.globalInstance().start(histWorker)
예제 #24
0
    def __init__(self):
        super().__init__()

        # Some buttons
        w = QWidget()
        l = QHBoxLayout()
        w.setLayout(l)

        btn_stop = QPushButton("Stop")

        l.addWidget(btn_stop)

        self.setCentralWidget(w)

        # Create a statusbar.
        self.status = self.statusBar()
        self.progress = QProgressBar()
        self.status.addPermanentWidget(self.progress)

        # Thread runner
        self.threadpool = QThreadPool()

        # Create a runner
        self.runner = JobRunner()
        self.runner.signals.progress.connect(self.update_progress)
        self.threadpool.start(self.runner)

        btn_stop.pressed.connect(self.runner.kill)

        self.show()
예제 #25
0
    def __init__(self):
        super().__init__()

        self.threadpool = QThreadPool()

        self.x = {}  # Keep timepoints.
        self.y = {}  # Keep data.
        self.lines = {}  # Keep references to plotted lines, to update.

        layout = QVBoxLayout()
        self.graphWidget = pg.PlotWidget()
        self.graphWidget.setBackground("w")
        layout.addWidget(self.graphWidget)

        button = QPushButton("Create New Worker")
        button.pressed.connect(self.execute)

        # layout.addWidget(self.progress)
        layout.addWidget(button)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()
예제 #26
0
파일: view.py 프로젝트: nitrotm/2dtagger
    def __init__(self, window):
        super(View, self).__init__(window)

        self.setFocusPolicy(Qt.StrongFocus)
        self.shiftKey = False
        self.ctrlKey = False
        self.lastMousePos = QPoint()
        self.lastTabletPos = QPoint()
        self.mode = 'add'
        self.maskOnly = False

        self.refresh = QTimer(self)
        self.refresh.setSingleShot(True)
        self.refresh.timeout.connect(self.repaint)

        self.addCursor = makeCursor('images/cursor-add.png',
                                    QColor.fromRgbF(0.5, 0.5, 1.0))
        self.delCursor = makeCursor('images/cursor-del.png',
                                    QColor.fromRgbF(1.0, 0.5, 0.5))
        self.setCursor(self.addCursor)

        self.imagefile = None
        self.maskfile = None
        self.image = QImage()
        self.mask = QImage(self.image.size(), QImage.Format_RGB32)
        self.mask.fill(Qt.black)
        self.changed = False
        self.update()

        self.path = list()

        self.load_threads = QThreadPool()
        self.load_threads.setMaxThreadCount(4)
예제 #27
0
    def __init__(self, parent=None, image_names=None):
        self.figure = Figure()
        super(ImageCanvas, self).__init__(self.figure)

        self.raw_axes = []  # only used for raw currently
        self.axes_images = []
        self.overlay_artists = {}
        self.cached_detector_borders = []
        self.saturation_texts = []
        self.cmap = hexrd.ui.constants.DEFAULT_CMAP
        self.norm = None
        self.iviewer = None
        self.azimuthal_integral_axis = None
        self.azimuthal_line_artist = None
        self.wppf_plot = None

        # Track the current mode so that we can more lazily clear on change.
        self.mode = None

        # Track the pixel size
        self.cartesian_res_config = (
            HexrdConfig().config['image']['cartesian'].copy())
        self.polar_res_config = HexrdConfig().config['image']['polar'].copy()

        # Set up our async stuff
        self.thread_pool = QThreadPool(parent)

        if image_names is not None:
            self.load_images(image_names)

        self.setup_connections()
예제 #28
0
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()

        self.progress = QProgressBar()

        button = QPushButton("START IT UP")
        button.pressed.connect(self.execute)

        self.status = QLabel("0 workers")

        layout.addWidget(self.progress)
        layout.addWidget(button)
        layout.addWidget(self.status)

        w = QWidget()
        w.setLayout(layout)

        # Dictionary holds the progress of current workers.
        self.worker_progress = {}

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print(
            "Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()
        )

        self.timer = QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.refresh_progress)
        self.timer.start()
예제 #29
0
    def __init__(self, mode: ApplicationMode, taskFilePath: str):
        super().__init__()
        self.mode = mode
        self.taskFilePath = taskFilePath
        self.initLogging()

        self.logger.info(f"Initializing application with mode: {mode}")

        SETTINGS = QtCore.QSettings(asset_manager.getMainSettingsPath(),
                                    QtCore.QSettings.IniFormat)

        self.appInfo = AppInfo()
        self.appInfo.company = SETTINGS.value("company")
        self.appInfo.appName = SETTINGS.value("app_name")
        self.mongodbHost = SETTINGS.value("mongodb_host")
        self.dbName = SETTINGS.value("db_name")
        self.hostProcessController = None
        self.serviceManager = None
        self.dbManager = None
        self.serviceRegistry = ServiceRegistry()

        dbInitTimeout = None
        if self.mode == ApplicationMode.GUI:
            self.app = QApplication([])
            self.loaderWindow = LoaderWindow(self.app, self.appInfo,
                                             self.logger, self)
        elif self.mode == ApplicationMode.Console:
            dbInitTimeout = 60.0
            self.consoleApp = ConsoleApp(self.appInfo,
                                         self.serviceRegistry,
                                         taskFilePath=self.taskFilePath,
                                         initTimeout=120.0)

        QThreadPool.globalInstance().start(
            qt_util.LambdaTask(self.initDataBaseManager, dbInitTimeout))
예제 #30
0
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()

        self.text = QPlainTextEdit()
        layout.addWidget(self.text)

        self.progress = QProgressBar()
        self.progress.setRange(0, 100)
        self.progress.setValue(0)
        layout.addWidget(self.progress)

        btn_run = QPushButton("Execute")
        btn_run.clicked.connect(self.start)

        layout.addWidget(btn_run)

        w = QWidget()
        w.setLayout(layout)
        self.setCentralWidget(w)

        # Thread runner
        self.threadpool = QThreadPool()

        self.show()
예제 #31
0
파일: ui_workload.py 프로젝트: pxlc/pxlc_td
class UiWorkLoadManager(QObject):

    def __init__(self):

        super().__init__()

        self.threadpool = QThreadPool()
        self.workload_info_by_name = {}

    def add_workload(self, workload_name: str, work_fn: Callable,
                     finished_callback_fn: Callable,
                     error_callback_fn: Callable,
                     result_callback_fn: Callable,
                     progress_callback_fn: Callable):

        self.workload_info_by_name[workload_name] = {
            'work_fn': work_fn,
            'finished_fn': finished_callback_fn,
            'error_fn': error_callback_fn,
            'result_fn': result_callback_fn,
            'progress_fn': progress_callback_fn,
        }

    def run_workload(self, workload_name: str, workload_data: dict):

        workload_info = self.workload_info_by_name[workload_name]
        ui_workload = _UiWorkLoad(workload_info['work_fn'], workload_data)

        ui_workload.signals.finished.connect(workload_info['finished_fn'])
        ui_workload.signals.error.connect(workload_info['error_fn'])
        ui_workload.signals.result.connect(workload_info['result_fn'])
        ui_workload.signals.progress.connect(workload_info['progress_fn'])

        self.threadpool.start(ui_workload)