def __init__(self, parent, container: Container) -> None: self.container = container self.ui = GeneralAppConfigUi(parent, container, self) self.ui.limit_memory.setMinimum(0) self.ui.limit_memory.setMaximum(utils.getPhysicalMemory() * 70 / 100) self.ui.limit_memory.setValue(self.container.memory_limit) self.ui.limit_memory.sliderReleased.connect(self.onMemoryChanged) self.ui.limit_memory.valueChanged.connect(self.onMemoryChanging) self.onMemoryChanging() self.ui.limit_cpu.setMinimum(0) self.ui.limit_cpu.setMaximum( int(QThread.idealThreadCount()) * 100 * 80 / 100) self.ui.limit_cpu.setValue(self.container.cpu_limit * 100) self.ui.limit_cpu.sliderReleased.connect(self.onCpuChanged) self.ui.limit_cpu.valueChanged.connect(self.onCpuChanging) self.onCpuChanging() self.retranslateUi() self.loadTags() self.ui.sync.clicked.connect(self.onSyncClicked) self.ui.container_name.textChanged.connect(self.onNameChanged) self.ui.image_tags.currentIndexChanged.connect(self.onImageTagChange) self.ui.entrypoint.textChanged.connect(self.onEntrypointChanged) self.ui.entrypoint.setText(container.entrypoint)
def __init__(self, source='', destination='', clear_destination=False): super(GCWii, self).__init__() self.export_in_progress = False app = QtWidgets.QApplication(sys.argv) self.MainWindow = QtWidgets.QMainWindow() self.max_treads = QThread.idealThreadCount() self.setupUi(self.MainWindow) self.msg = MessageBox() self.manager = GCWiiManager() self.default_box_artwork = str(os.path.join('images', 'blanc-case.png')) self.default_disc_artwork = str( os.path.join('images', 'blanc-disc.png')) self.source_directory = source self.source_game_collection = {} self.destination_directory = destination self.clear_destination = clear_destination self.destination_game_collection = {} self.box_artwork_path = os.path.join(os.getcwd(), 'images', 'cover3D') self.disc_artwork_path = os.path.join(os.getcwd(), 'images', 'disc') self.current_selection = {} self.games_to_export = {} self.setup_widgets() self.setup_actions() self.MainWindow.show() if self.source_directory: self.update_source_list() if self.destination_directory: self.update_destination_list() sys.exit(app.exec_())
def train_start(self, signal): print("Your computer's Ideal Thread Number :", QThread.idealThreadCount()) if signal is 'start': self.thread = Worker(self.parent, 1) self.thread.start() # run() else: QThread.terminate() self.thread.terminate() self.thread.quit()
def __init__(self, iface): self.iface = iface self.canvas = self.iface.mapCanvas() threadcount = QThread.idealThreadCount() # use all available cores and parallel rendering QgsApplication.setMaxThreads(threadcount) QSettings().setValue("/qgis/parallel_rendering", True) # OpenCL acceleration QSettings().setValue("/core/OpenClEnabled", True) self.dlg = None
def __init__(self, max_threads: int = None): super().__init__() self.running_threads: List[ThreadWrapper] = [] self.pending_threads: List[ThreadWrapper] = [] self.running_thread_count = 0 if max_threads is None: self.max_threads = QThread.idealThreadCount() else: self.max_threads = max_threads if self.max_threads < 1: self.max_threads = 1
def __init__(self): super().__init__() titol = 'Descarregador de vídeos de YouTube' self.setWindowTitle(titol) self.setMinimumSize(600, 600) self.layout = QVBoxLayout() self.centralWidget = QWidget(self) self.centralWidget.setLayout(self.layout) self.setCentralWidget(self.centralWidget) self.lblTitol = QLabel(titol, self.centralWidget) self.lblTitol.setFont(QFont('Segoe UI Light', 14, QFont.Bold)) self.layout.addWidget(self.lblTitol) self.lblTextExplicacio = QLabel( 'Introdueix els enllaços dels vídeos que vols descarregar, separats per espais i/o salts de línia.\nTot el que hi hagi a partir del caràcter # serà ignorat.', self.centralWidget) self.layout.addWidget(self.lblTextExplicacio) self.layoutProces = QVBoxLayout() self.layoutProces.setSpacing(0) self.layout.addLayout(self.layoutProces) self.textEdit = QTextEdit(self.centralWidget) self.textEdit.textChanged.connect( lambda: self.botoDescarregar.setEnabled(self.textEdit.toPlainText( ) != '')) self.layout.addWidget(self.textEdit) self.layoutInferior = QHBoxLayout() self.layout.addLayout(self.layoutInferior) self.cbMP3 = QCheckBox('Descarrega només àudio', self) self.layoutInferior.addWidget(self.cbMP3) layoutThreads = QHBoxLayout() lblThreads = QLabel('Nombre de fils:') self.cbThreads = QComboBox(self.centralWidget) self.cbThreads.addItems( [str(i) for i in range(1, QThread.idealThreadCount())]) self.cbThreads.setCurrentIndex(self.cbThreads.count() - 1) layoutThreads.addWidget(lblThreads) layoutThreads.addWidget(self.cbThreads) self.layoutInferior.addLayout(layoutThreads) self.layoutInferior.addStretch() self.botoDescarregar = QPushButton('Descarregar', self.centralWidget) self.botoDescarregar.setEnabled(False) self.layoutInferior.addWidget(self.botoDescarregar) self.botoDescarregar.clicked.connect(self.descarrega) self.defineixMenuBar()
def __init__(self, imageOptions=None, parent=None, dialog=None): QObject.__init__(self, parent) self._imageOptions = imageOptions self._threads = [] for i in range(QThread.idealThreadCount()): thread = QdImageLoaderThread(self) self._threads.append(thread) #self.connect(thread, SIGNAL('loaded(QString, QImage)'), self.loaded) thread.loaded.connect(self.loaded) #self.connect(thread, SIGNAL('finished()'), self.threadFinished) thread.finished.connect(self.threadFinished) self._stopped = True self._paths = [] self._index = 0 #self.connect( dialog, SIGNAL('rejected()'), self.terminateLoading ) dialog.rejected.connect(self.terminateLoading)
def __init__(self, iface): """ Contructor """ self.iface = iface log.initLogging() threadcount = QThread.idealThreadCount() # use all available cores and parallel rendering QgsApplication.setMaxThreads(threadcount) QSettings().setValue("/qgis/parallel_rendering", True) # OpenCL acceleration QSettings().setValue("/core/OpenClEnabled", True) self.plugin_dir = os.path.dirname(__file__) locale = QSettings().value("locale//userLocale")[0:2] localePath = os.path.join( self.plugin_dir, 'i18n', 'qgisfmv_{}.qm'.format(locale)) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '5.9.0': QCoreApplication.installTranslator(self.translator) self._FMVManager = None
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'ImageViewer_{}.qm'.format(locale)) threadcount = QThread.idealThreadCount() # use all available cores and parallel rendering QgsApplication.setMaxThreads(threadcount) QSettings().setValue("/qgis/parallel_rendering", True) # OpenCL acceleration QSettings().setValue("/core/OpenClEnabled", True) self.canvas = self.iface.mapCanvas() self.dlg1 = None if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&Image Viewer')
# self.timer.setInterval(1) # self.timer.start() # # self.exec_() except Exception: pass def timeClock(self): try: value = int(time.time() - self.timeStart) print("value", str(value)) # with open("value","a")as file: # file.write(str(value)) # except Exception as e: print(str(e)) if __name__ == '__main__': print(QThread.idealThreadCount()) app = QApplication(sys.argv) clockThread = ClockThread() clockThread.start() print(clockThread.isRunning()) #clockThread.exit() app.exec_() #
class ExampleThread(Qt.QWidget): def __init__(self, parent=None): super(ExampleThread, self).__init__(parent) layout = Qt.QVBoxLayout(self) self.lbl = Qt.QLabel("Start") layout.addWidget(self.lbl) self.btnA = Qt.QPushButton("Запустить AThread(QThread)") layout.addWidget(self.btnA) self.btnB = Qt.QPushButton("Запустить SomeObject(QObject)") layout.addWidget(self.btnB) self.btnC = Qt.QPushButton("Запустить Worker(QRunnable)") layout.addWidget(self.btnC) self.progressBar = Qt.QProgressBar() self.progressBar.setProperty("value", 0) layout.addWidget(self.progressBar) self.setGeometry(550, 65, 300, 300) self.setWindowTitle('3 разных и простых способа работы с потоками.') self.btnA.clicked.connect(self.using_q_thread) self.btnB.clicked.connect(self.using_move_to_thread) self.btnC.clicked.connect(self.using_q_runnable) self.msg = MsgBoxAThread() self.thread = None self.msgSomeObject = MsgBoxSomeObject() self.objThread = None self.counter = 0 self.timer = Qt.QTimer() self.timer.setInterval(1000) # -------- timeout -------> def recurring_timer(self): self.timer.timeout.connect(self.recurring_timer) self.timer.start() self.threadpool = QThreadPool() print("Max потоков, кот. будут использоваться=`%d`" % self.threadpool.maxThreadCount()) self.msgWorker = MsgBoxWorker() self.threadtest = QThread(self) self.idealthreadcount = self.threadtest.idealThreadCount() print("Ваша машина может обрабатывать `{}` потокa оптимально.".format(self.idealthreadcount)) def recurring_timer(self): self.counter += 1 self.lbl.setText("СЧЁТЧИК цикл GUI: %d" % self.counter) # ---- AThread(QThread) -----------# def using_q_thread(self): if self.thread is None: self.thread = AThread() self.thread.threadSignalAThread.connect(self.on_threadSignalAThread) self.thread.finished.connect(self.finishedAThread) self.thread.start() self.btnA.setText("Stop AThread(QThread)") else: self.thread.terminate() self.thread = None self.btnA.setText("Start AThread(QThread)") def finishedAThread(self): self.thread = None self.btnA.setText("Start AThread(QThread)") def on_threadSignalAThread(self, value): self.msg.label.setText(str(value)) # Восстанавливаем визуализацию потокового окна, если его закрыли. Поток работает. # .setVisible(true) или .show() устанавливает виджет в видимое состояние, # если видны все его родительские виджеты до окна. if not self.msg.isVisible(): self.msg.show() # --END-- AThread(QThread) -------------------# # ---- SomeObject(QObject) -------------------# def using_move_to_thread(self): if self.objThread is None: self.objThread = QThread() self.obj = SomeObject() self.obj.moveToThread(self.objThread) # Переместить в поток для выполнения self.obj.threadSignalSomeObject.connect(self.on_threadSignalSomeObject) self.obj.finishedSomeObject.connect(self.finishedSomeObject) self.objThread.started.connect(self.obj.long_running) self.objThread.start() self.btnB.setText("Wait SomeObject(QObject)") self.btnB.setEnabled(False) else: pass def finishedSomeObject(self): self.objThread.terminate() self.objThread.wait(1) self.objThread = None self.btnB.setEnabled(True) self.btnB.setText("Start SomeObject(QObject)") def on_threadSignalSomeObject(self, value): self.msgSomeObject.label.setText(str(value)) # Восстанавливаем визуализацию потокового окна, если его закрыли. Поток работает. if not self.msgSomeObject.isVisible(): self.msgSomeObject.show() # --END-- SomeObject(QObject) -------------------# # ---- Worker(QRunnable) ------------------------# def using_q_runnable(self): # Передайте функцию для выполнения # Любые другие аргументы, kwargs передаются функции run worker = Worker(self.execute_this_fn) worker.signals.result.connect(self.print_output) worker.signals.finish.connect(self.thread_complete) worker.signals.progress.connect(self.progress_fn) self.threadpool.start(worker) def progress_fn(self, n): self.progressBar.setValue(n) self.msgWorker.label.setText(str(n)) # Восстанавливаем визуализацию потокового окна, если его закрыли. Поток работает. if not self.msgWorker.isVisible(): self.msgWorker.show() def execute_this_fn(self, progress_callback): for n in range(0, 11): Qt.QThread.msleep(600) progress_callback.emit(n * 100 / 10) return "Готово." def print_output(self, s): print("\ndef print_output(self, s):", s) def thread_complete(self): print("\nTHREAD ЗАВЕРШЕН!, self->", self) # --END-- Worker QRunnable) -------------------# # ==============================================### # потоки или процессы должны быть завершены ### def closeEvent(self, event): reply = Qt.QMessageBox.question \ (self, 'Информация', "Вы уверены, что хотите закрыть приложение?", Qt.QMessageBox.Yes, Qt.QMessageBox.No) if reply == Qt.QMessageBox.Yes: if self.thread: self.thread.quit() del self.thread self.msg.close() if self.objThread: self.objThread.setTerminationEnabled(True) self.objThread.terminate() self.objThread.wait(1) self.msgSomeObject.close() # закрыть поток Worker(QRunnable) self.msgWorker.close() super(ExampleThread, self).closeEvent(event) else: event.ignore()
def __init__(self, *args, **kwargs): super(ThumbnailMaker, self).__init__(*args, **kwargs) self.queue = [] self.running = 0 self.queue_max = QThread.idealThreadCount()
def __init__(self, parent=None, db="", config="", ng=None): """ Constructor """ QWizard.__init__(self, parent) self.setupUi(self) self.URLgroupBox.setVisible(True) self.URLFileGroupBox.setVisible(False) self.bingGroupBox.setVisible(False) self.ng = ng self.db = db if db: self.currentDatabase = db.name else: self.currentDatabase = "" self.configName.setText(config) self.problemBox.hide() self.selectedBaseGroupBox.setTitle("selected base: " + self.currentDatabase) self.coreLabel.setText("This computer has %i cores." % QThread.idealThreadCount()) self.expertButton = self.button(self.CustomButton1) self.expertButton.setIcon( QtGui.QIcon(QtGui.QPixmap(":images/images/expert.png"))) self.expertButton.setToolTip("toggle expert mode") self.expertButton.setCheckable(True) # self.expertButton.toggle() self.expertObjects = [ "baseInfoFrame", "takePdf", "pageIgnoreCase", "defaultEncodingFrame", "textLabelMaxSubdomains", "maxSubdomains", "pathGroupBox", "linkRestriction", "spiderTraps", "timeout", "trytimes", "timeoutsec", "followRedirects", "parallelGroupBox", "identityGroupBox", "politenessGroupBox", "proxyGroupBox", "levelFrom", "levelTo", "levelFromLabel", "levelToLabel" ] self.expert(self.expertButton.isChecked()) self.diskSizeInfoLabel.setText("of the " + str( utils.get_free_space( os.path.join(os.path.expanduser('~'), "gromoteur", "corpora")) ) + " Mb of free space in the corpus folder") for lang in sorted(self.ng.alllangs.values()): self.language.addItem(str(lang)) for ua in userAgents: self.userAgent.addItem(str(ua)) # print "*********************************" self.checkConfigName() # print "============", list(self.findChildren(QtGui.QCheckBox,QtCore.QRegExp(r'\w*'))) # self.specialStringObjectList=[self.searchEngineQuery] self.stringObjectList = list(self.findChildren(QtWidgets.QLineEdit)) self.stringObjectList = [ c for c in self.stringObjectList if c.objectName() != "qt_spinbox_lineedit" and not c.isReadOnly() and c.objectName() != "configName" ] self.checkObjectList = list( self.findChildren(QtWidgets.QCheckBox)) + list( self.findChildren(QtWidgets.QGroupBox)) + list( self.findChildren( QtWidgets.QRadioButton)) + [self.expertButton] self.checkObjectList = [ c for c in self.checkObjectList if c.isCheckable() ] self.valueObjectList = list(self.findChildren(QtWidgets.QSpinBox)) self.valueObjectList = [ c for c in self.valueObjectList if not c.isReadOnly() ] self.comboObjectList = list(self.findChildren(QtWidgets.QComboBox)) self.nbpages.setText(str(self.db.nbPages)) self.nbsentences.setText(str(self.db.nbSentences)) self.nbwords.setText(str(self.db.nbCharacters)) self.comments.setPlainText(self.db.comments) if self.db.nbPages == 0: self.fromdatabase.setEnabled(False) self.fromdatabase.setChecked(False) self.dataErase.setChecked(True) else: self.fromdatabase.setEnabled(True) self.lff = LoseFocusFilter(self) self.downloadURL.installEventFilter(self.lff) self.downloadAvoidURL.installEventFilter(self.lff) self.pageRestriction.installEventFilter(self.lff) self.linkDomain.installEventFilter(self.lff) self.linkAvoidURL.installEventFilter(self.lff) self.downloadURL.wiz = self self.downloadAvoidURL.wiz = self self.pageRestriction.wiz = self self.linkDomain.wiz = self self.linkAvoidURL.wiz = self self.language.setEnabled(True) self.webSearchUrl = None