def updateLogList(self, logsAdded=None, logsRenamed=None): selectedMember = self.get_selected_log_member() if logsAdded == None: self.log_tree_view.clear() logsAdded = [] for index, logFile in enumerate(reversed(self.listLogFilesForMember(selectedMember))): logsAdded.append((index, logFile)) if len(logsAdded) == 0: self.log_tree_view.clear() self.log_tree_view.addTopLevelItem( QTreeWidgetItem(self.log_tree_view, QStringList("No logs available.")) ) self.log_tree_view.setSelectionMode(QTreeWidget.NoSelection) self.logSizeLabel.setText("No logs") self.clearLogsButton.setEnabled(False) return if logsRenamed != None: for index, oldName, newName in logsRenamed: # index + 1 because of the "requesting" item item = self.log_tree_view.topLevelItem(index + 1) if item != None: itemLogFile = convert_string(item.data(0, Qt.UserRole).toString()) if itemLogFile != oldName: self.logger.warning( "index does not correspond to item in list:\n\t%s\n\t%s", itemLogFile, oldName ) self.initializeLogItem(item, newName) if len(logsAdded) == 0: self.log_tree_view.takeTopLevelItem(0) else: for index, logFile in logsAdded: oldItem = self.log_tree_view.topLevelItem(index) item = None if oldItem != None and oldItem.data(0, Qt.UserRole) == None: # requested item has been received item = oldItem else: item = QTreeWidgetItem() oldItem = None if logFile == None: item.setData(0, Qt.DisplayRole, QVariant("Requesting...")) QTimer.singleShot(6000, partial(self.requestTimedOut, item)) else: self.initializeLogItem(item, logFile) if oldItem == None: # else, the old item is being modified self.log_tree_view.insertTopLevelItem(index, item) self.log_tree_view.setSelectionMode(QTreeWidget.SingleSelection) totalSize = 0 for aLogFile in self.listLogFilesForMember(selectedMember): totalSize += os.path.getsize(aLogFile) self.logSizeLabel.setText("%s consumed" % self.formatFileSize(totalSize)) self.clearLogsButton.setEnabled(True)
def __init__( self, parent = None ): """ Constructor """ super( FrmDevolucion, self ).__init__( parent ) self.editmodel = None self.status = True # las acciones deberian de estar ocultas # El modelo principal self.navmodel = RONavigationModel( self ) # El modelo que filtra a self.navmodel self.navproxymodel = QSortFilterProxyModel( self ) self.navproxymodel.setSourceModel( self.navmodel ) # Este es el modelo con los datos de la tabla para navegar self.detailsmodel = QSqlQueryModel( self ) # Este es el filtro del modelo anterior self.detailsproxymodel = QSortFilterProxyModel( self ) self.detailsproxymodel.setSourceModel( self.detailsmodel ) # Cargar los modelos en un hilo aparte QTimer.singleShot( 0, self.loadModels )
def _loadFinished(self, ok): self.log("_loadFinished %s" % id(self.splash_request)) if self.deferred.called: # sometimes this callback is called multiple times self.log("_loadFinished called multiple times") return page_ok = ok and self.web_page.errorInfo is None maybe_redirect = not ok and self.web_page.errorInfo is None error_loading = ok and self.web_page.errorInfo is not None if maybe_redirect: self.log("Redirect or other non-fatal error detected %s" % id(self.splash_request)) # XXX: It assumes loadFinished will be called again because # redirect happens. If redirect is detected improperly, # loadFinished won't be called again, and Splash will return # the result only after a timeout. # # FIXME: This can happen if server returned incorrect # Content-Type header; there is no an additional loadFinished # signal in this case. return if page_ok: time_ms = int(self.wait_time * 1000) QTimer.singleShot(time_ms, self._loadFinishedOK) elif error_loading: self.log("loadFinished %s: %s" % (id(self.splash_request), str(self.web_page.errorInfo))) # , min_level=1) # XXX: maybe return a meaningful error page instead of generic # error message? self.deferred.errback(RenderError()) else: self.log("loadFinished %s: unknown error" % id(self.splash_request)) # , min_level=1) self.deferred.errback(RenderError())
def start(self, fetch_config, options): action = self.init_worker(fetch_config, options) assert callable(action), "%s should be callable" % action self.thread.start() # this will be called in the worker thread. QTimer.singleShot(0, action) self.running_state_changed.emit(True)
def __init__(self): QMainWindow.__init__(self) self.setupUi(self) self._config = {} SubscriberApplication.instance().subscribed.connect(self.statusBar().clearMessage) SubscriberApplication.instance().subscriptionError.connect(self._subscriptionError) QTimer.singleShot(0, self._chooseTeam)
def __init__( self, tiposdoc, parent = None, edit = True ): ''' Constructor ''' super( FrmKardex, self ).__init__( parent ) self.tiposdoc = ",".join( [str( item ) for item in tiposdoc] ) self.edit = edit self.navigationmodel = QSqlQueryModel() self.detailsModel = QSqlQueryModel() self.navproxymodel = QSortFilterProxyModel() self.navproxymodel.setSourceModel( self.navigationmodel ) self.detailsproxymodel = QSortFilterProxyModel() self.detailsproxymodel.setSourceModel( self.detailsModel ) self.tabledetails.setModel( self.detailsproxymodel ) self.tablenavigation.setModel( self.navproxymodel ) self.editmodel = None QTimer.singleShot( 0, self.loadModels )
def show(self, webPages): settings = Settings() server = xmlrpclib.Server(settings.serverAddress) self.setWindowTitle('updates') layout = self.layout() if layout == None: layout = QVBoxLayout() label = QLabel('Some Web Pages have changed:') layout.addWidget(label) for webPage in webPages: label = QLabel('<a href=' + webPage + '>' + self._truncate(webPage) + '</a>' ) label.setOpenExternalLinks(True) layout.addWidget(label) #buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) moreButton = QPushButton('More...') moreButton.setMaximumWidth(60) self.connect(moreButton, SIGNAL('clicked()'), self.showDiffWindow) layout.addWidget(moreButton) self.setLayout(layout) if debug.verbose: print('DEBUG: Showing notification dialog') QDialog.show(self) QTimer.singleShot(0, self.fixPosition) QTimer.singleShot(self._timeout, self.hide)
def refreshActionIfNeeded(self, checked=False): if backend.STATUS.devStatusChanged() or backend.STATUS.mountStatusChanged(): # wait a moment after change detected # (let the system create device files, etc..) # sometimes, an exception occurs here (for 500ms delay): # "Could not find IO device path" BlockDevice.__init__() QTimer.singleShot(int(2 * self._checkInterval), self.refreshAction)
def __init__(self, argv): QMainWindow.__init__(self) #Normalize the data if true self._normalize_data=True if 'notnormalize' in sys.argv: print sys.argv self._normalize_data=False sys.argv.remove('notnormalize') self.opPredict = None self.opTrain = None self.opThreshold = None self._colorTable16 = self._createDefault16ColorColorTable() #self.g = Graph(7, 2048*1024**2*5) self.g = Graph() self.fixableOperators = [] self.featureDlg=None #The old ilastik provided the following scale names: #['Tiny', 'Small', 'Medium', 'Large', 'Huge', 'Megahuge', 'Gigahuge'] #The corresponding scales are: self.featScalesList=[0.3, 0.7, 1, 1.6, 3.5, 5.0, 10.0] self.initUic() #if the filename was specified on command line, load it if len(sys.argv) >= 2: def loadFile(): self._openFile(sys.argv[1:]) QTimer.singleShot(0, loadFile)
def run_method(self): def renderer_func(): renderer = WebkitRenderer() renderer.width = 0 renderer.height = 0 renderer.timeout = 10 renderer.wait = 1 renderer.format = "png" renderer.grabWholeWindow = False for url in self.listOfUrls: url = url[0] fileName = url.split('://') if len(fileName) >1: fileName = fileName[1].split('www.') else: fileName = fileName[0].split('www.') if len(fileName) >1: fileName = fileName[1].split('.') else: fileName = fileName[0].split('.') fileName = fileName[0] outfile = open("%s.png" % fileName, "w") renderer.render_to_file(url, outfile) outfile.close() app = init_qtgui() QTimer.singleShot(0, renderer_func) app.exec_() sys.exit(1)
def __init__(self): # init the widget #QWidget.__init__(self, parent) # set up the scene self.scene=QGraphicsScene() self.scene.setSceneRect(0,0,800,600) # add a view of that scene self.view = QGraphicsView() self.view.setScene(self.scene) self.view.setRenderHint(QPainter.Antialiasing) self.view.setFixedSize(800,600) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # set the screen sync to vertical retrace val = "1" # Set for nVidia linux os.environ["__GL_SYNC_TO_VBLANK"] = val # Set for recent linux Mesa DRI Radeon os.environ["LIBGL_SYNC_REFRESH"] = val qglf = QGLFormat() qglf.setSampleBuffers(True) self.glw = QGLWidget(qglf) self.glw.setAutoBufferSwap(False) self.view.setViewport(self.glw) #self.view.showFullScreen() self.view.show() self.last_finish = 0 QTimer.singleShot(0,self.glw.swapBuffers)
def waitForSignal(signal, message="", timeout=0): """Waits (max timeout msecs if given) for a signal to be emitted. It the waiting lasts more than 2 seconds, a progress dialog is displayed with the message. Returns True if the signal was emitted. Return False if the wait timed out or the dialog was canceled by the user. """ loop = QEventLoop() dlg = QProgressDialog(minimum=0, maximum=0, labelText=message) dlg.setWindowTitle(appinfo.appname) dlg.setWindowModality(Qt.ApplicationModal) QTimer.singleShot(2000, dlg.show) dlg.canceled.connect(loop.quit) if timeout: QTimer.singleShot(timeout, dlg.cancel) stop = lambda: loop.quit() signal.connect(stop) loop.exec_() signal.disconnect(stop) dlg.hide() dlg.deleteLater() return not dlg.wasCanceled()
def on_chatView_loadFinished(self, ok=True): self._bodyElement = self.chatView.page().mainFrame().documentElement().findFirst('body') # check that the body element is really loaded, otherwise try again later if self._bodyElement.isNull(): QTimer.singleShot(100, self.on_chatView_loadFinished) return self._showHistoryMessages()
def __init__( self, what, options, path = "", buf = "", parent = None ): QDialog.__init__( self, parent ) self.__cancelRequest = False self.__inProgress = False self.__what = what self.__options = options self.__path = path # could be a dir or a file self.__buf = buf # content in case of a modified file # Working process data self.__participantFiles = [] # Collected list of files self.__projectImportDirs = [] self.__projectImportsCache = {} # utils.settings -> /full/path/to.py self.__dirsToImportsCache = {} # /dir/path -> { my.mod: path.py, ... } self.dataModel = ImportDiagramModel() self.scene = QGraphicsScene() # Avoid pylint complains self.progressBar = None self.infoLabel = None self.__createLayout() self.setWindowTitle( 'Imports/dependencies diagram generator' ) QTimer.singleShot( 0, self.__process ) return
def test_repaint_after_visible_change(self): self.model = LayerStackModel() self.o1 = Layer([]) self.o1.name = "Fancy Layer" self.o1.opacity = 0.5 self.model.append(self.o1) self.o2 = Layer([]) self.o2.name = "Some other Layer" self.o2.opacity = 0.25 self.model.append(self.o2) self.view = LayerWidget(None, self.model) self.view.show() self.view.updateGeometry() self.w = QWidget() self.lh = QHBoxLayout(self.w) self.lh.addWidget(self.view) self.w.setGeometry(100, 100, 300, 300) self.w.show() # Run the test within the GUI event loop QTimer.singleShot(500, self.impl ) self.app.exec_() # Were there errors? assert not TestLayerWidget.errors, "There were GUI errors/failures. See above."
def createWidget(self): import widget w = widget.MusicView(self) w.zoomChanged.connect(self.slotMusicZoomChanged) w.updateZoomInfo() w.view.surface().selectionChanged.connect(self.updateSelection) import qpopplerview.pager self._pager = p = qpopplerview.pager.Pager(w.view) p.pageCountChanged.connect(self.slotPageCountChanged) p.currentPageChanged.connect(self.slotCurrentPageChanged) app.languageChanged.connect(self.updatePagerLanguage) selector = self.actionCollection.music_document_select selector.currentDocumentChanged.connect(w.openDocument) selector.documentClosed.connect(w.clear) if selector.currentDocument(): # open a document only after the widget has been created; # this prevents many superfluous resizes def open(): if selector.currentDocument(): w.openDocument(selector.currentDocument()) QTimer.singleShot(0, open) return w
def wrapper(self): instantiated = bool(super(panel.Panel, self).widget()) self.activate() if instantiated: func(self) else: QTimer.singleShot(0, lambda: func(self))
def startShellGui(workflow_cmdline_args, eventcapture_mode, playback_args, preinit_funcs, postinit_funcs): """ Create an application and launch the shell in it. """ """ The next two lines fix the following xcb error on Ubuntu by calling X11InitThreads before loading the QApplication: [xcb] Unknown request in queue while dequeuing [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called [xcb] Aborting, sorry about that. python: ../../src/xcb_io.c:178: dequeue_pending_request: Assertion !xcb_xlib_unknown_req_in_deq failed. """ platform_str = platform.platform().lower() if "ubuntu" in platform_str or "fedora" in platform_str or "debian" in platform_str: QApplication.setAttribute(Qt.AA_X11InitThreads, True) if ilastik.config.cfg.getboolean("ilastik", "debug"): QApplication.setAttribute(Qt.AA_DontUseNativeMenuBar, True) if eventcapture_mode is not None: # Only use a special QApplication subclass if we are recording. # Otherwise, it's a performance penalty for every event processed by Qt. from eventcapture.eventRecordingApp import EventRecordingApp app = EventRecordingApp.create_app(eventcapture_mode, **playback_args) else: app = QApplication([]) _applyStyleSheet(app) splashScreen.showSplashScreen() app.processEvents() QTimer.singleShot(0, functools.partial(launchShell, workflow_cmdline_args, preinit_funcs, postinit_funcs)) QTimer.singleShot(0, splashScreen.hideSplashScreen) return app.exec_()
def bisection_finished(self, bisection, resultcode): if resultcode == Bisection.USER_EXIT: msg = "Bisection stopped." dialog = QMessageBox.information elif resultcode == Bisection.NO_DATA: msg = "Unable to find enough data to bisect." dialog = QMessageBox.warning elif resultcode == Bisection.EXCEPTION: msg = "Error: %s" % self.bisector.error[1] dialog = QMessageBox.critical else: if bisection.fetch_config.can_go_inbound() and \ isinstance(bisection.handler, NightlyHandler): # we can go on inbound, let's ask the user if QMessageBox.question( self.mainwindow, "End of the bisection", "Nightly bisection is done, but you can continue the" " bisection on inbound builds. Contibue with inbounds ?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes ) == QMessageBox.Yes: # let's go on inbound QTimer.singleShot(0, self.bisector.nightlies_to_inbound) else: # no inbound, bisection is done. self.stop() return msg = "The bisection is done." dialog = QMessageBox.information dialog(self.mainwindow, "End of the bisection", msg) self.stop()
def refresh(self): """Updates view(s).""" index = self.stackedWidget.currentIndex() if index == 1: self.populatedTable = False self.selectedWidget.clear() self.getAllSelected() elif index == 0: self.populatedTree = False self.treeWidget.clear() self.treeWidget.setDisabled(True) bnField = "ItemTracker ID" self.selectedIds = {} self.errorIds = {} selection = DB.Db.Selection self.selectedIds, self.errorIds = bn.getItemIds(bnField, selection) if len(self.selectedIds): self.strainInfo = {} self.itemIds = {} self.getBnFields() # self.populateTree() QTimer.singleShot(0, self.populateTree) elif index == 2: self.populatedCherry = False QTimer.singleShot(0, self.cherryPicking) self.updateUi()
def getAllSelected(self): """Get all selected items by user.""" if self.populatedTable: self.stackedWidget.setCurrentIndex(1) self.updateUi() return msg = "Getting all selected entries from ItemTracker. Please wait..." self.statusbar.showMessage(msg) if len(self.itemIdsAll): try: self.tableResults = \ lims.SelectAllselectedEntries(self.itemIdsAll.keys()) except: raise RuntimeError else: self.mkInfo("No ItemTracker IDs to process") if not len(self.tableResults): user = os.environ.get("USERNAME") msg = "No selected entries for user {0}".format(user) self.statusbar.showMessage(msg, 5000) self.mkInfo(msg) self.stackedWidget.setCurrentIndex(1) self.populatedTable = False self.updateUi() else: QTimer.singleShot(0, self.populateTable)
def wrapper(*args): self = args[0] def execWithArgs(): core.mainWindow().show() QTest.qWaitForWindowShown(core.mainWindow()) func(*args) # When done processing these events, exit the event loop. QTimer.singleShot(0, self.app.quit) QTimer.singleShot(0, execWithArgs) # Catch any exceptions which the EventLoop would otherwise catch # and not re-raise. exceptions = [] def excepthook(type_, value, tracebackObj): exceptions.append((value, tracebackObj)) if PRINT_EXEC_TRACKBACK: oldExcHook(type_, value, tracebackObj) self.app.quit() oldExcHook = sys.excepthook sys.excepthook = excepthook try: # Run the requested function in the application's main loop. self.app.exec_() # If an exception occurred in the event loop, re-raise it. if exceptions: value, tracebackObj = exceptions[0] raise value, None, tracebackObj finally: # Restore the old exception hook sys.excepthook = oldExcHook
def matlEdit(self): self.dirty= True self.updateStatus("Call edit material code here") # This ends up in a little child window self.matlPopup= QLabel("<font color=green size=72><b> Material Editor </b></font>") # self.matlPopup.setWindowFlags(Qt.SplashScreen) self.matlPopup.setWindowTitle("Material edit popup") self.matlPropsHere= QLabel("<font color=red size=24><b> Data goes here </b></font>") # self.matlPopup.setWindowFlags(Qt.SplashScreen) if 1 == 0: dataLayout= QVBoxLayout() dataLayout.addWidget(self.matlPopup) dataLayout.addWidget(self.matlPropsHere) self.setLayout(dataLayout) self.matlPopup.show() self.matlPropsHere.show() # self.exampleForm= MatlForm() # First need a layout manager, and add the widget to that. # Then attach the layout manager to a window. # addWidget(self.exampleForm) # self.exampleForm.show() QTimer.singleShot(5000, self.update) self.updateStatus("Created stackup db")
def slot_fileRefresh(self): if self.fWebFrame is None: return self.ui.label_progress.setText(self.tr("Refreshing UI...")) self.ui.stackedwidget.setCurrentIndex(0) QTimer.singleShot(0, self.slot_fileRefreshPost)
def slot_webviewPostFinished(self): if self.fNextBundle: bundle = self.fNextBundle self.fNextBundle = "" self.fWebFrame.evaluateJavaScript("desktop.loadPedalboard(\"%s\")" % bundle) QTimer.singleShot(0, self.slot_webviewPostFinished2)
def exceptionCaught(self, message, package = '', block = False): self.runPreExceptionMethods() if any(warning in message for warning in ('urlopen error','Socket Error', 'PYCURL ERROR')): errorTitle = i18n("Network Error") errorMessage = i18n("Please check your network connections and try again.") elif "Access denied" in message or "tr.org.pardus.comar.Comar.PolicyKit" in message: errorTitle = i18n("Authorization Error") errorMessage = i18n("You are not authorized for this operation.") elif "HTTP Error 404" in message and not package == '': errorTitle = i18n("Pisi Error") errorMessage = unicode(i18n("Package <b>%s</b> not found in repositories.<br>"\ "It may be upgraded or removed from the repository.<br>"\ "Please try upgrading repository informations.")) % package elif "MIXING PACKAGES" in message: errorTitle = i18n("Pisi Error") errorMessage = i18n("Mixing file names and package names not supported yet.") elif "FILE NOT EXISTS" in message: errorTitle = i18n("Pisi Error") errorMessage = unicode(i18n("File <b>%s</b> doesn't exists.")) % package elif "ALREADY RUNNING" in message: errorTitle = i18n("Pisi Error") errorMessage = i18n("Another instance of PiSi is running. Only one instance is allowed.") else: errorTitle = i18n("Pisi Error") errorMessage = message self.messageBox = QMessageBox(errorTitle, errorMessage, QMessageBox.Critical, QMessageBox.Ok, 0, 0) if block: self.messageBox.exec_() self.runPostExceptionMethods() else: QTimer.singleShot(0, self.messageBox.exec_) self.messageBox.buttonClicked.connect(self.runPostExceptionMethods)
def cb_import_extract(result): script_instance = script_instance_ref[0] if script_instance != None: aborted = script_instance.abort else: aborted = False script_instance_ref[0] = None if aborted: return if not report_script_result(result, 'Import Error', 'Could not extract archive', before_message_box=self.progress.close): return def cb_restart_reboot_shutdown(result): self.progress.close() report_script_result(result, 'Import Error', 'Could not reboot RED Brick to finish program import') # step 4/4: reboot self.progress.setLabelText('Step 4 of 4: Rebooting RED Brick') self.progress.setRange(0, 0) self.script_manager.execute_script('restart_reboot_shutdown', cb_restart_reboot_shutdown, ['1']) def close_progress(): # use a closure to capture self and ansure that it's safe # to call this even if the tab was official destroyed already self.progress.close() QTimer.singleShot(1500, close_progress)
def openDialog(self, openDialogFunc, runInDialogFunc): """Open dialog by executing ``openDialogFunc`` and run ``runInDialogFunc``. Dialog is passed as a parameter to ``runInDialogFunc`` """ DELAY = 20 ATTEMPTS = 50 def isDialogsChild(dialog, widget): if widget is None: return False return widget is dialog or \ isDialogsChild(dialog, widget.parentWidget()) def timerCallback(attempt): if self._finished: return dialog = self._findDialog() if dialog is not None and \ isDialogsChild(dialog, self.app.focusWidget()): runInDialogFunc(dialog) else: if attempt < ATTEMPTS: QTimer.singleShot(20, lambda: timerCallback(attempt + 1)) else: self.fail("Dialog not found") QTimer.singleShot(20, lambda: timerCallback(1)) openDialogFunc()
def scheduleCall(func, *args, **kwargs): def wrapper(): try: func(*args, **kwargs) except: logger.exception("an unexpected exception occured in scheduleCall().") QTimer.singleShot(0, wrapper)
def stop(self): """Finish and cleanup.""" self.disconnectFromHost() while self.state() != self.UnconnectedState: d = defer.Deferred() QTimer.singleShot(100, lambda: d.callback(None)) yield d
def stopSpidering(self): print('stopSpidering') self.keep_spidering = False QTimer.singleShot(50, self, SIGNAL('stopSpidering()'))
def startApp(self): self.sessionManager = sessionManager(self._server) # Crear el manejador de la sessión self.sessionManager.splash.show() # Mostrar la pantalla splash QTimer.singleShot(5000, lambda: self.sessionManager.splash.hide()) # Ocultamiento de la pantalla splash QTimer.singleShot(5500, lambda: self.sessionManager.show()) # Despliegue del manejador de sessiones return exit(self.exec_()) # Bucle principal de la aplicación
def __init__(self): super().__init__() self._connection = None self.data_desc_table = None self.database_desc = None vbox = gui.vBox(self.controlArea, "Server", addSpace=True) box = gui.vBox(vbox) self.servertext = QtGui.QLineEdit(box) self.servertext.setPlaceholderText('Server') self.servertext.setToolTip('Server') if self.host: self.servertext.setText(self.host if not self.port else '{}:{}'. format(self.host, self.port)) box.layout().addWidget(self.servertext) self.databasetext = QtGui.QLineEdit(box) self.databasetext.setPlaceholderText('Database[/Schema]') self.databasetext.setToolTip('Database or optionally Database/Schema') if self.database: self.databasetext.setText( self.database if not self.schema else '{}/{}'. format(self.database, self.schema)) box.layout().addWidget(self.databasetext) self.usernametext = QtGui.QLineEdit(box) self.usernametext.setPlaceholderText('Username') self.usernametext.setToolTip('Username') if self.username: self.usernametext.setText(self.username) box.layout().addWidget(self.usernametext) self.passwordtext = QtGui.QLineEdit(box) self.passwordtext.setPlaceholderText('Password') self.passwordtext.setToolTip('Password') self.passwordtext.setEchoMode(QtGui.QLineEdit.Password) if self.password: self.passwordtext.setText(self.password) box.layout().addWidget(self.passwordtext) tables = gui.hBox(box) self.tablecombo = QtGui.QComboBox( tables, minimumContentsLength=35, sizeAdjustPolicy=QtGui.QComboBox.AdjustToMinimumContentsLength) self.tablecombo.setToolTip('table') tables.layout().addWidget(self.tablecombo) self.tablecombo.activated[int].connect(self.select_table) self.connectbutton = gui.button(tables, self, '↻', callback=self.connect) self.connectbutton.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) tables.layout().addWidget(self.connectbutton) self.custom_sql = gui.vBox(box) self.custom_sql.setVisible(False) self.sqltext = QtGui.QTextEdit(self.custom_sql) self.sqltext.setPlainText(self.sql) self.custom_sql.layout().addWidget(self.sqltext) mt = gui.hBox(self.custom_sql) cb = gui.checkBox(mt, self, 'materialize', 'Materialize to table ') cb.setToolTip('Save results of the query in a table') le = gui.lineEdit(mt, self, 'materialize_table_name') le.setToolTip('Save results of the query in a table') self.executebtn = gui.button(self.custom_sql, self, 'Execute', callback=self.open_table) box.layout().addWidget(self.custom_sql) gui.checkBox(box, self, "guess_values", "Auto-discover discrete variables", callback=self.open_table) gui.checkBox(box, self, "download", "Download data to local memory", callback=self.open_table) gui.rubber(self.buttonsArea) QTimer.singleShot(0, self.connect)
def onReplyError(self): weatherText = self.trUtf8("不能获取天气信息") self.gotResult.emit(weatherText, ":/images/weather/weather-none-available.png") QTimer.singleShot(0, self.deleteReply)
def process_events(): app.processEvents() #setup system natoms = 13 system = LJCluster(natoms) system.params.double_ended_connect.local_connect_params.NEBparams.iter_density = 5. x1, e1 = system.get_random_minimized_configuration()[:2] x2, e2 = system.get_random_minimized_configuration()[:2] db = Database() min1 = db.addMinimum(e1, x1) min2 = db.addMinimum(e2, x2) #setup neb dialog pl.ion() # pl.show() dlg = NEBDialog() wnd = dlg.nebwgt dlg.show() wnd.process_events.connect(process_events) #initilize the NEB and run it. #we have to do it through QTimer because the gui has to #be intitialized first... I don't really understand it from PyQt4.QtCore import QTimer QTimer.singleShot(10, start) sys.exit(app.exec_())
def enterEvent(self, event): self.setFixedSize( self._activeSize ) #this is the optical feedback when a touchscreen is in use QTimer.singleShot(500, lambda: self.resetSize())
def __del__(self): print('~~~~ Python label object destroyed') def setText(self, text): print('~~~~ Changing label text') QLabel.setText(self, text) def close(self): print('~~~~ Closing label') QLabel.close(self) app = QApplication([]) app.setQuitOnLastWindowClosed(False) label = Label() label.show() lineEdit = QLineEdit() lineEdit.textChanged.connect(onLineEditTextChanged) lineEdit.textChanged.connect(label.setText) QTimer.singleShot(1000, label.close) QTimer.singleShot(2000, changeLineEditText) QTimer.singleShot(3000, app.quit) app.exec_() print('~~~~ Application exited')
def clearSpiderPendingResponses(self): QTimer.singleShot(50, self, SIGNAL('clearSpiderPendingResponses()'))
def populateExistingSpiderData(self): QTimer.singleShot(50, self, SIGNAL('populateExistingSpiderData()'))
def resetSpiderPendingResponses(self): QTimer.singleShot(50, self, SIGNAL('resetSpiderPendingResponses()'))
from functools import partial from PyQt4.QtCore import QTimer from PyQt4.QtGui import QApplication tags = vigra.defaultAxistags("xyzc") tags['x'].resolution = 2.0 tags['y'].resolution = 2.0 tags['c'].description = 'rgb' app = QApplication([]) axistags_editor = AxistagsEditorWidget(None) axistags_editor.init(tags) axistags_editor.show() axistags_editor.adjustSize() axistags_editor.raise_() def handle_update(): print "Axistags were updated: {}".format(axistags_editor.axistags) axistags_editor.axistagsUpdated.connect(handle_update) # Change the order after 2 seconds QTimer.singleShot(2000, partial(axistags_editor.change_axis_order, "tyxc")) app.exec_() # Print the final edited values print "FINAL AXISTAGS:" print axistags_editor.axistags.toJSON()
def clearSpiderQueue(self): QTimer.singleShot(50, self, SIGNAL('clearSpiderQueue()'))
def mousePressEvent(self, event): self.emit(SIGNAL("clicked()")) # Use busy cursor for 2 secs self.setCursor(Qt.WaitCursor) QTimer.singleShot(2000, self, SLOT("slot_setNormalCursor()")) QLabel.mousePressEvent(self, event)
def __init__(self, parent=None, autoupdate=Event()): QWidget.__init__(self, parent) # self.app = QApplication(sys.argv) # window = QMainWindow() self.my_gauge = Ui_MainWindow() self.my_gauge.setupUi(self) self.maxButton_NameTextLenght = 15 # Max charcters # self.my_gauge.name_list.setFont() self.my_gauge.widget.enable_barGraph = True self.my_gauge.widget.value_needle_snapzone = 1 self.my_gauge.widget.set_scale_polygon_colors([[.0, Qt.green], [.1, Qt.green], [.25, Qt.yellow], [.55, Qt.blue], [.95, Qt.darkBlue]]) # self.my_gauge.ActualSlider.setMaximum(self.my_gauge.widget.value_max) # self.my_gauge.ActualSlider.setMinimum(self.my_gauge.widget.value_min) # self.my_gauge.AussenRadiusSlider.setValue(self.my_gauge.widget.gauge_color_outer_radius_factor * 1000) # self.my_gauge.InnenRadiusSlider.setValue(self.my_gauge.widget.gauge_color_inner_radius_factor * 1000) # self.my_gauge.GaugeStartSlider.setValue(self.my_gauge.widget.scale_angle_start_value) # self.my_gauge.GaugeSizeSlider.setValue(self.my_gauge.widget.scale_angle_size) self.my_gauge.pushButton.clicked.connect(self.start_timer) self.my_gauge.pushButton_openfile.clicked.connect(self.openfile_read_list) self.my_gauge.pushButton_clear.clicked.connect(self.clear_name_list_widget) self.my_gauge.name_list.itemSelectionChanged.connect(self.item_selection_changed) self.my_gauge.checkBox_toggle_info.stateChanged.connect(self.toggle_info) # self.my_gauge.widge self.my_gauge.widget.set_enable_ScaleText(False) self.autoupdate = autoupdate self.starten = Event() self.stoppen = Event() self.new_data = Queue() self.reset = Event() self.my_queue = Queue() button_x_size = 30 button_y_size = 30 x_pos = 20 y_pos = 0 self.button_ring =(QPushButton(str("sec"), self)) self.button_ring.setGeometry(x_pos, y_pos, button_x_size, button_y_size) self.button_ring.clicked.connect(self.set_timer_seconds) self.button_ring.move(x_pos - button_x_size / 2, y_pos) # + button_y_size / 2) self.button_ring.show() self.button_panel =(QPushButton(str(">"), self)) self.button_panel.setGeometry(x_pos+button_x_size, y_pos, button_x_size, button_y_size) self.button_panel.clicked.connect(self.toggle_panel) self.button_panel.move((x_pos - button_x_size / 2) + button_x_size, y_pos) # + button_y_size / 2) self.button_panel.show() text_x_size = 500 text_y_size = 75 self.name_highlight = QLabel(self) self.name_highlight.setGeometry(x_pos+(button_x_size*2), 0, text_x_size, text_y_size) self.name_highlight.move(x_pos + button_x_size*2 - button_x_size/2, -20) # self.name_highlight.setGeometry(30, 30, text_x_size, text_y_size) # self.name_highlight.move(70, -10) self.name_highlight.setText("") myfont = QFont("Segoe UI", 30) myfont.setBold(True) self.name_highlight.setFont(myfont) self.name_highlight.show() self.panel_show = True # self.toggle_button_label_info = False self.toggle_button_label_info = self.my_gauge.checkBox_toggle_info.checkState() # self.toggle_info() self.toggle_show_name_label() self.my_gauge.checkBox_show_name_label.stateChanged.connect(self.toggle_show_name_label) # Disable standard AnalogGaugeWidget float value, to replace with human readable time values self.my_gauge.widget.set_enable_value_text(False) self.my_gauge.widget.enable_user_defined_value_text = True self.running = sut(self.starten, self.stoppen, self.reset, self.my_queue, self.new_data) self.running.start() self.set_time(30) time.sleep(0.1) # self.starten.set() self.state_dict = {"init": "start", "reset": "start", "start": "stop", "stop": "reset"} self.actual_state = "init" print(self.actual_state) # add banner image banner_name = "banner.png" banner_path = os.path.dirname(__file__) + os.path.sep + banner_name self.pixmap = QPixmap(banner_path) # self.pixmap = self.pixmap.scaledToWidth(300) self.my_gauge.banner.setPixmap(self.pixmap) self.my_gauge.banner.setScaledContents(True) self.my_gauge.widget.initial_value_fontsize = 50 QTimer.singleShot(10, self.check_new_data) self.update() self.toggle_info()
def __init__(self, parent=None, signalManager=None, title="CSV File Import"): OWWidget.__init__(self, parent, signalManager, title, wantMainArea=False, noReport=True) self.symbol_DC = "" self.symbol_DK = "" #: List of recent opened files. self.recent_files = [] #: Current selected file name self.selected_file = None #: Variable reuse flag self.create_new_on = 2 #: Display advanced var reuse options self.show_advanced = False self.loadSettings() self.recent_files = filter(os.path.exists, self.recent_files) self._loader = None self._invalidated = False self._datareport = None layout = QHBoxLayout() OWGUI.widgetBox(self.controlArea, "File", orientation=layout) icons = standard_icons(self) self.recent_combo = QComboBox(self, objectName="recent_combo", toolTip="Recent files.", activated=self.activate_recent) cb_append_file_list(self.recent_combo, self.recent_files) self.recent_combo.insertSeparator(self.recent_combo.count()) self.recent_combo.addItem(u"Browse documentation data sets…") self.browse_button = QPushButton(u"…", icon=icons.dir_open_icon, toolTip="Browse filesystem", clicked=self.browse) self.reload_button = QPushButton("Reload", icon=icons.reload_icon, toolTip="Reload the selected file", clicked=self.reload, default=True) layout.addWidget(self.recent_combo, 2) layout.addWidget(self.browse_button) layout.addWidget(self.reload_button) ########### # Info text ########### box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True) self.infoa = OWGUI.widgetLabel(box, "No data loaded.") self.infob = OWGUI.widgetLabel(box, " ") self.warnings = OWGUI.widgetLabel(box, " ") # Set word wrap so long warnings won't expand the widget self.warnings.setWordWrap(True) self.warnings.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.MinimumExpanding) advanced = QGroupBox("Advanced Settings", checkable=True, checked=self.show_advanced) advanced.setLayout(QVBoxLayout()) def set_group_visible(groupbox, state): layout = groupbox.layout() for i in range(layout.count()): item = layout.itemAt(i) widget = item.widget() if widget is not None: widget.setVisible(state) groupbox.setFlat(not state) def toogle_advanced(state): self.show_advanced = state set_group_visible(advanced, state) self.layout().activate() QApplication.instance().processEvents() QTimer.singleShot(0, self.adjustSize) advanced.toggled.connect(toogle_advanced) self.taboptions = QWidget() self.taboptions.setLayout(QVBoxLayout()) box = QGroupBox("Missing Value Symbols", flat=True) form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow) form.addRow( "Don't care:", OWGUI.lineEdit(None, self, "symbol_DC", tooltip="Default values: '~' or '*'")) form.addRow( "Don't know:", OWGUI.lineEdit(None, self, "symbol_DK", tooltip="Default values: empty fields (space), " "'?' or 'NA'")) box.setLayout(form) advanced.layout().addWidget(box) rb = OWGUI.radioButtonsInBox( advanced, self, "create_new_on", box="New Attributes", callback=self._invalidate, label=u"Create a new attribute when existing attribute(s) …", btnLabels=[ u"Have mismatching order of values", u"Have no common values with the new (recommended)", u"Miss some values of the new attribute", u"… Always create a new attribute" ]) rb.setFlat(True) self.controlArea.layout().addWidget(advanced) button_box = QDialogButtonBox(orientation=Qt.Horizontal) self.import_options_button = QPushButton(u"Import Options…", enabled=False) self.import_options_button.pressed.connect( self._activate_import_dialog) button_box.addButton(self.import_options_button, QDialogButtonBox.ActionRole) button_box.addButton( QPushButton("&Report", pressed=self.reportAndFinish), QDialogButtonBox.ActionRole) self.controlArea.layout().addWidget(button_box) OWGUI.rubber(self.controlArea) set_group_visible(advanced, self.show_advanced) if self.recent_files and self.recent_files[0] == self.selected_file: QTimer.singleShot(0, lambda: self.activate_recent(0)) else: self.selected_file = None self.recent_combo.setCurrentIndex(-1)
def __init__(self, newer=None, parent=None): super(QVersionDownloader, self).__init__(parent=parent) self.setupUi(self) QTimer.singleShot(0, lambda: self._download(newer))
def __init__(self, manager, url, handler, encoding="UTF-8"): HtmlReplyBase.__init__(self, manager, url, handler, encoding) self.callHandler() self.outputReady() QTimer.singleShot(0, self.emitSignals)
def toogle_advanced(state): self.show_advanced = state set_group_visible(advanced, state) self.layout().activate() QApplication.instance().processEvents() QTimer.singleShot(0, self.adjustSize)
def handle_merge(self, bisection, branch, good_rev, bad_rev): self.worker.fetch_config.set_repo(str(branch)) bisection.handler.good_revision = str(good_rev) bisection.handler.bad_revision = str(bad_rev) QTimer.singleShot(0, self.worker.bisect_further)
def runImportList(self, importers, proxy_filelist, source, callback): self.importers = importers self.proxy_filelist = proxy_filelist self.source = source self.callbackObj = callback QTimer.singleShot(50, self, SIGNAL('do_runImport()'))
def __init__(self, parent): super(AudioVideoTab, self).__init__(parent) self.parent = parent self.name = 'AudioVideo' self.defaultStr = self.tr('Default') self.DisableStream = self.tr('Disable') self.formats = config.video_formats frequency_values = [self.defaultStr] + config.video_frequency_values bitrate_values = [self.defaultStr] + config.video_bitrate_values rotation_options = [ self.tr('None'), '90 ' + self.tr('clockwise'), '90 ' + self.tr('clockwise') + ' + ' + self.tr('vertical flip'), '90 ' + self.tr('counter clockwise'), '90 ' + self.tr('counter clockwise') + ' + ' + self.tr('vertical flip'), '180', self.tr('horizontal flip'), self.tr('vertical flip') ] digits_validator = QRegExpValidator(QRegExp(r'[1-9]\d*'), self) digits_validator_wzero = QRegExpValidator(QRegExp(r'\d*'), self) digits_validator_minus = QRegExpValidator(QRegExp(r'(-1|[1-9]\d*)'), self) time_validator = QRegExpValidator( QRegExp(r'\d{1,2}:\d{1,2}:\d{1,2}\.\d+'), self) converttoQL = QLabel(self.tr('Convert to:')) self.extQCB = QComboBox() self.extQCB.setMinimumWidth(100) vidcodecQL = QLabel('Video codec:') self.vidcodecQCB = QComboBox() self.vidcodecQCB.setMinimumWidth(110) audcodecQL = QLabel('Audio codec:') self.audcodecQCB = QComboBox() self.audcodecQCB.setMinimumWidth(110) hlayout1 = utils.add_to_layout('h', converttoQL, self.extQCB, QSpacerItem(180, 20), vidcodecQL, self.vidcodecQCB, audcodecQL, self.audcodecQCB) commandQL = QLabel(self.tr('Command:')) self.commandQLE = QLineEdit() self.presetQPB = QPushButton(self.tr('Preset')) self.defaultQPB = QPushButton(self.defaultStr) hlayout2 = utils.add_to_layout('h', commandQL, self.commandQLE, self.presetQPB, self.defaultQPB) sizeQL = QLabel(self.tr('Video Size:')) aspectQL = QLabel(self.tr('Aspect:')) frameQL = QLabel(self.tr('Frame Rate (fps):')) bitrateQL = QLabel(self.tr('Video Bitrate (kbps):')) self.widthQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) self.heightQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) label = QLabel('<html><p align="center">x</p></html>') layout1 = utils.add_to_layout('h', self.widthQLE, label, self.heightQLE) self.aspect1QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) self.aspect2QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) label = QLabel('<html><p align="center">:</p></html>') layout2 = utils.add_to_layout('h', self.aspect1QLE, label, self.aspect2QLE) self.frameQLE = utils.create_LineEdit((120, 16777215), digits_validator, 4) self.bitrateQLE = utils.create_LineEdit((130, 16777215), digits_validator, 6) labels = [sizeQL, aspectQL, frameQL, bitrateQL] widgets = [layout1, layout2, self.frameQLE, self.bitrateQLE] self.preserveaspectQChB = QCheckBox(self.tr("Preserve aspect ratio")) self.preservesizeQChB = QCheckBox(self.tr("Preserve video size")) preserve_layout = utils.add_to_layout('v', self.preserveaspectQChB, self.preservesizeQChB) videosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) videosettings_layout.addLayout(layout) if a == aspectQL: # add vidaspectCB in layout after aspectQL videosettings_layout.addLayout(preserve_layout) freqQL = QLabel(self.tr('Frequency (Hz):')) chanQL = QLabel(self.tr('Audio Channels:')) bitrateQL = QLabel(self.tr('Audio Bitrate (kbps):')) threadsQL = QLabel(self.tr('Threads:')) self.freqQCB = QComboBox() self.freqQCB.addItems(frequency_values) self.chan1QRB = QRadioButton('1') self.chan1QRB.setMaximumSize(QSize(51, 16777215)) self.chan2QRB = QRadioButton('2') self.chan2QRB.setMaximumSize(QSize(51, 16777215)) self.group = QButtonGroup() self.group.addButton(self.chan1QRB) self.group.addButton(self.chan2QRB) spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) chanlayout = utils.add_to_layout('h', spcr1, self.chan1QRB, self.chan2QRB, spcr2) self.audbitrateQCB = QComboBox() self.audbitrateQCB.addItems(bitrate_values) self.threadsQLE = utils.create_LineEdit((50, 16777215), digits_validator_wzero, 1) labels = [freqQL, bitrateQL, chanQL, threadsQL] widgets = [ self.freqQCB, self.audbitrateQCB, chanlayout, self.threadsQLE ] audiosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) audiosettings_layout.addLayout(layout) time_format = " (hh:mm:ss):" beginQL = QLabel(self.tr("Split file. Begin time") + time_format) self.beginQLE = utils.create_LineEdit(None, time_validator, None) durationQL = QLabel(self.tr("Duration") + time_format) self.durationQLE = utils.create_LineEdit(None, time_validator, None) hlayout4 = utils.add_to_layout('h', beginQL, self.beginQLE, durationQL, self.durationQLE) embedQL = QLabel(self.tr("Embed subtitle:")) self.embedQLE = QLineEdit() self.embedQTB = QToolButton() self.embedQTB.setText("...") rotateQL = QLabel(self.tr("Rotate:")) self.rotateQCB = QComboBox() self.rotateQCB.addItems(rotation_options) hlayout5 = utils.add_to_layout('h', rotateQL, self.rotateQCB, embedQL, self.embedQLE, self.embedQTB) hidden_layout = utils.add_to_layout('v', videosettings_layout, audiosettings_layout, hlayout4, hlayout5) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.moreQPB = QPushButton(QApplication.translate('Tab', 'More')) self.moreQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.moreQPB.setCheckable(True) hlayout3 = utils.add_to_layout('h', line, self.moreQPB) self.frame = QFrame() self.frame.setLayout(hidden_layout) self.frame.hide() final_layout = utils.add_to_layout('v', hlayout1, hlayout2, hlayout3, self.frame) self.setLayout(final_layout) self.presetQPB.clicked.connect(self.choose_preset) self.defaultQPB.clicked.connect(self.set_default_command) self.embedQTB.clicked.connect(self.open_subtitle_file) self.moreQPB.toggled.connect(self.frame.setVisible) self.moreQPB.toggled.connect( lambda: QTimer.singleShot(100, self.resize_parent)) self.widthQLE.textChanged.connect(self.command_update_size) self.heightQLE.textChanged.connect(self.command_update_size) self.aspect1QLE.textChanged.connect(self.command_update_aspect) self.aspect2QLE.textChanged.connect(self.command_update_aspect) self.frameQLE.textChanged.connect(self.command_update_frames) self.bitrateQLE.textChanged.connect(self.command_update_vidbitrate) self.threadsQLE.textChanged.connect(self.command_update_threads) self.beginQLE.textChanged.connect(self.command_update_begin_time) self.durationQLE.textChanged.connect(self.command_update_duration) self.embedQLE.textChanged.connect(self.command_update_subtitles) self.vidcodecQCB.currentIndexChanged.connect( self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect( self.command_update_acodec) self.freqQCB.currentIndexChanged.connect(self.command_update_frequency) self.rotateQCB.currentIndexChanged.connect( self.command_update_rotation) self.audbitrateQCB.currentIndexChanged.connect( self.command_update_audbitrate) self.chan1QRB.clicked.connect( lambda: self.command_update_channels('1')) self.chan2QRB.clicked.connect( lambda: self.command_update_channels('2')) self.preserveaspectQChB.toggled.connect( self.command_update_preserve_aspect) self.preservesizeQChB.toggled.connect( self.command_update_preserve_size)
def __init__(self, parent=None, fakeStartup=False, filename=None): ''' Constructor ''' self._fakeStartup = fakeStartup super(DrumBurp, self).__init__(parent) self._state = None self._asciiSettings = None self._printer = None self.setupUi(self) self.scoreScene = None self.paperBox.blockSignals(True) self.paperBox.clear() self._knownPageHeights = [] printer = QPrinter() printer.setOutputFileName("invalid.pdf") for name in dir(QPrinter): attr = getattr(QPrinter, name) if (isinstance(attr, QPrinter.PageSize) and name != "Custom"): self.paperBox.addItem(name) printer.setPaperSize(attr) self._knownPageHeights.append(printer.pageRect().height()) self._pageHeight = printer.paperRect().height() self.paperBox.blockSignals(False) settings = self._makeQSettings() self.recentFiles = [ unicode(fname) for fname in settings.value("RecentFiles").toStringList() if os.path.exists(unicode(fname)) ] if filename is None: filename = (None if len(self.recentFiles) == 0 else self.recentFiles[0]) self.filename = filename self.addToRecentFiles() self.updateRecentFiles() self.songProperties = QDisplayProperties() # Create scene errored_files = [] try: self.scoreScene = QScore(self) except: errored_files.append(self.filename) try: self.recentFiles.remove(self.filename) except ValueError: pass self.filename = None self.scoreScene = QScore(self) self.restoreGeometry(settings.value("Geometry").toByteArray()) self.restoreState(settings.value("MainWindow/State").toByteArray()) self.statusbar.addPermanentWidget(QFrame()) self.availableNotesLabel = QLabel() self.availableNotesLabel.setMinimumWidth(250) self.statusbar.addPermanentWidget(self.availableNotesLabel) self._infoBar = QLabel() self.statusbar.addPermanentWidget(self._infoBar) self._initializeState() self.setSections() self._versionThread = VersionCheckThread() self._versionThread.finished.connect(self._finishedVersionCheck) QTimer.singleShot(0, lambda: self._startUp(errored_files)) self.actionCheckOnStartup.setChecked( settings.value("CheckOnStartup").toBool())
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.piece = ["P", "N", "B", "R", "Q", "K"] self.callList = [] self.timer = QTimer() self.initGui() cmdline = ["./genchess", ""] self.engine = Process(cmdline) self.newGame() def __del__(self): pass def initGui(self): self.connect(self, SIGNAL('triggered()'), self.closeEvent) self.connect(self.actionNew_Game_F2, SIGNAL("triggered()"), self.newGame) for i in range(6): self.connect(self.whiteButtons[i], SIGNAL("clicked()"), lambda n="w" + str(i): self.runButton(n)) self.connect(self.blackButtons[i], SIGNAL("clicked()"), lambda n="b" + str(i): self.runButton(n)) for i in range(64): self.connect(self.boardButtons[i], SIGNAL("clicked()"), lambda n="n" + str(i): self.runButton(n)) self.iconMap = {} list = listdir("./Images/") for item in list: icon = QIcon() icon.addFile("./Images/" + item) self.iconMap[item[0] + item[1]] = icon for i in range(0, 6): self.whiteButtons[i].setIcon(self.iconMap["W"+self.piece[i]]) self.blackButtons[i].setIcon(self.iconMap["B"+self.piece[i]]) def closeEvent(self, event): self.engine.write("quit\n") sleep(0.2) self.engine.terminate() def comExe(self, data, lines): self.engine.write(data) output = self.engine.read() while len(output.splitlines()) < lines: sleep(0.05) output += self.engine.read() return output def displayMessage(self, msg): self.statusbar.showMessage(msg) def updateBoard(self, move): color = ["W", "B"] color = color[self.stm] if move[0] in self.piece: to = boardIndex(move[1:]) self.board[to] = color + move[0] self.boardButtons[to].setIcon(self.iconMap[self.board[to]]) return fr = boardIndex(move[0:2]) to = boardIndex(move[2:4]) self.board[to] = self.board[fr] self.boardButtons[fr].setIcon(self.iconMap["EE"]) self.boardButtons[to].setIcon(self.iconMap[self.board[to]]) def runComputer(self): data = self.comExe("go\n", 2).splitlines() move = data[0].split()[1] results = data[1].split()[0] self.updateBoard(move) msg = color[self.stm] + "'s move: " + move if results == 'ok': self.displayMessage(msg) elif results == 'special': self.displayMessage(msg + ' (' + dropWord(data[1]) + ')') elif results == 'result': self.displayMessage(msg + ' ' + dropWord(data[1], 2)) return self.stm ^= True self.callList = [] self.timer.singleShot(300, self.nextPlayer) def nextPlayer(self): if player[self.stm] == 'computer': self.runComputer() def newGame(self): self.engine.write("newgame\n") for i in range(64): self.boardButtons[i].setIcon(self.iconMap["EE"]) self.stm = False self.board = [''] * 64 self.nextPlayer() def runButton(self, n): if n[0] == "w" or n[0] == "b": if len(self.callList) == 1 and self.callList[0] in self.piece: self.callList = [ self.piece[int(n[1:])] ] self.displayMessage("active button: " + self.callList[0]) return self.callList.append(self.piece[int(n[1:])]) else: self.callList.append(boardCord(int(n[1:]))) if len(self.callList) == 1: self.displayMessage("active button: " + self.callList[0]) return elif self.callList[1][0] in self.piece: self.statusbar.clearMessage() self.callList = [] return elif self.callList[0] == self.callList[1]: self.statusbar.clearMessage() self.callList = [] return act = ''.join(self.callList) self.callList = [] data = self.comExe("move " + act + '\n', 1) results = data.split()[0] if results == 'ok': self.displayMessage(color[self.stm] + "'s move: " + act) self.updateBoard(act) self.stm ^= True elif results == 'special': self.displayMessage(color[self.stm] + "'s move: " + act + " (" + dropWord(data) + ")") self.updateBoard(act) self.stm ^= True elif results == 'illegal': self.displayMessage(data) elif results == 'result': self.displayMessage(color[self.stm] + "'s move: " + act + " " + dropWord(data, 2)) self.updateBoard(act) return self.timer.singleShot(300, self.nextPlayer)
def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # set the default properties of the volume slider self.volumeSlider.setMinimum(0) self.volumeSlider.setMaximum(100) self.volumeSlider.setValue(50) self.volumeSlider.setTickInterval(1) # set fake value for the elapsed time slider self.elapsedTimeSlider.setMinimum(0) # instantiate the MusicPlayer object self.player = MusicPlayer() #instantiate the PlaylistManager object self.playlist_manager = PlaylistManager() # setting the methods to be called self.playButton.clicked.connect(self.playPauseAudio) self.stopButton.clicked.connect(self.stopAudio) self.browseButton.clicked.connect(self.browseFs) self.volumeSlider.valueChanged.connect(self.changeVolume) self.elapsedTimeSlider.sliderReleased.connect(self.seek_song_position) self.player.eosReached.connect(self.play_next_song) #self.player.playingSet.connect(self.set_song_duration) self.songsListWidget.itemDoubleClicked.connect(self.play_song) self.playlistListWidget.itemClicked.connect( self.create_playlist_songs_list) # set icons for the button self.stopButton.setIcon(QtGui.QIcon('./icons/stop.png')) self.playButton.setIcon(QtGui.QIcon('./icons/play.png')) # set model in tree view #self.build_file_system() # create music list from file system self.populate_song_list_from_fs() # create playlists list self.populate_playlist_list() # create context menus: song list.. self.songsListWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.songsListWidget.customContextMenuRequested.connect( self.onSongContext) # ..and playlists list self.playlistListWidget.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.playlistListWidget.customContextMenuRequested.connect( self.onPlaylistContext) # timer used to update the slider which shows the elapsed time of a song self.durationTimer = QTimer() self.durationTimer.timeout.connect(self.set_song_elapsed_time) self.durationTimer.start(1000) # Single shot timer used to parse all the playlist in background QTimer.singleShot(1000, self.parse_playlists_songs) # register a function that GLib will call every second #GLib.timeout_add_seconds(1, self.get_stream_duration) self.addPlaylistButton.clicked.connect(self.add_new_playlist)
def disconnected(signal, slot): """ A context manager disconnecting a slot from a signal. :: with disconnected(scene.selectionChanged, self.onSelectionChanged): # Can change item selection in a scene without # onSelectionChanged being invoked. do_something() """ signal.disconnect(slot) try: yield finally: signal.connect(slot) if __name__ == "__main__": app = QApplication(sys.argv) w = OWKEGGPathwayBrowser() w.show() data = Orange.data.Table("brown-selected.tab") QTimer.singleShot(3000, lambda: w.SetData(data)) QTimer.singleShot(3500, w.handleNewSignals) app.exec_() w.saveSettings()
# Library imports # --------------- import sys import os # Third-party imports # ------------------- # Instead of creating a custom .spec file: inform PyInstaller of the # hidden import of QtWebKit, which is performed inside of uic.loadUi. from PyQt4.QtWebKit import QWebView # Other Qt imports used in the code below. from PyQt4.QtGui import QApplication, QDialog from PyQt4 import uic from PyQt4.QtCore import QTimer # Local imports # ------------- from pyi_get_datadir import get_data_dir # Test code # --------- app = QApplication([]) window = QDialog() uic.loadUi(os.path.join(get_data_dir(), 'PyQt4_uic', 'PyQt4-uic.ui'), window) window.show() # Exit Qt when the main loop becomes idle. QTimer.singleShot(0, app.exit) # Run the main loop, displaying the WebKit widget. app.exec_()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Other attributes... self.segmentation = None self.operation = "no" self.applyInclusion = False self.applyExclusion = False self.applySampling = True self.samplingRate = 100 self.createdInputs = list() self.folderLabels = list() self.selectedfolderLabels = list() self.rootFolderPath = u'' self.inclusionsUser = u'' self.exclusionsUser = u'' self.newAnnotationKey = u'' self.newAnnotationValue = u'' self.folders = list() # self.folders is a list of dictionaries with each dictionaries being a a folder self.inclusionList = [".txt",".html",".xml",".csv"] #by default empty list # self.exclusionList = [".png,",".PNG",".jpg",".JPG",".gif",".GIF",".tiff",".TIFF",".jpeg",".JPEG",".DS_Store"] # by default exclusions : img files, .DS_Store (macOS) self.exclusionList = [] # by default null self.infoBox = InfoBox(widget=self.controlArea) # self.fileList = list() #output file list self.sendButton = SendButton( widget=self.controlArea, master=self, callback=self.sendData, infoBoxAttribute='infoBox', sendIfPreCallback=self.updateGUI, ) self.advancedSettings = AdvancedSettings( widget=self.controlArea, master=self, callback=self.sendButton.settingsChanged, ) # GUI... # Advanced settings checkbox... self.advancedSettings.draw() # BASIC GUI... # Basic folder box basicfolderBox = gui.widgetBox( widget=self.controlArea, box=u'Source', orientation='vertical', addSpace=False, ) basicfolderBoxLine1 = gui.widgetBox( widget=basicfolderBox, box=False, orientation='horizontal', ) gui.lineEdit( widget=basicfolderBoxLine1, master=self, value='rootFolderPath', orientation='horizontal', label=u'Folder path:', labelWidth=101, callback=self.add, tooltip=( u"The path of the folder." ), ) gui.separator(widget=basicfolderBoxLine1, width=5) gui.button( widget=basicfolderBoxLine1, master=self, label=u'Browse', callback=self.browse, tooltip=( u"Open a dialog for selecting a top folder." ), ) #gui.separator(widget=basicfolderBox, width=3) #gui.comboBox( # widget=basicfolderBox, # master=self, # value='encoding', # items=getPredefinedEncodings(), # sendSelectedValue=True, # orientation='horizontal', # label=u'Encoding:', # labelWidth=101, # callback=self.sendButton.settingsChanged, # tooltip=( # u"Select input folder(s) encoding." # ), # ) gui.separator(widget=basicfolderBox, width=3) self.advancedSettings.basicWidgets.append(basicfolderBox) self.advancedSettings.basicWidgetsAppendSeparator() # ADVANCED GUI... # folder box folderBox = gui.widgetBox( widget=self.controlArea, box=u'Sources', orientation='vertical', addSpace=False, ) folderBoxLine1 = gui.widgetBox( widget=folderBox, box=False, orientation='horizontal', addSpace=True, ) self.folderListbox = gui.listBox( widget=folderBoxLine1, master=self, value='selectedfolderLabels', labels='folderLabels', callback=self.updatefolderBoxButtons, tooltip=( u"The list of folders whose content will be imported.\n" u"\nIn the output segmentation, the content of each\n" u"folder appears in the same position as in the list.\n" u"\nColumn 1 shows the folder's name.\n" u"Column 2 shows the folder's annotation (if any).\n" u"Column 3 shows the folder's encoding." ), ) font = QFont() font.setFamily('Courier') font.setStyleHint(QFont.Courier) font.setPixelSize(12) self.folderListbox.setFont(font) folderBoxCol2 = gui.widgetBox( widget=folderBoxLine1, orientation='vertical', ) self.moveUpButton = gui.button( widget=folderBoxCol2, master=self, label=u'Move Up', callback=self.moveUp, tooltip=( u"Move the selected folder upward in the list." ), ) self.moveDownButton = gui.button( widget=folderBoxCol2, master=self, label=u'Move Down', callback=self.moveDown, tooltip=( u"Move the selected folder downward in the list." ), ) self.removeButton = gui.button( widget=folderBoxCol2, master=self, label=u'Remove', callback=self.remove, tooltip=( u"Remove the selected folder from the list." ), ) self.clearAllButton = gui.button( widget=folderBoxCol2, master=self, label=u'Clear All', callback=self.clearAll, tooltip=( u"Remove all folders from the list." ), ) self.exportButton = gui.button( widget=folderBoxCol2, master=self, label=u'Export List', callback=self.exportList, tooltip=( u"Open a dialog for selecting a folder where the folder\n" u"list can be exported in JSON format." ), ) self.importButton = gui.button( widget=folderBoxCol2, master=self, label=u'Import List', callback=self.importList, tooltip=( u"Open a dialog for selecting a folder list to\n" u"import (in JSON format). folders from this list\n" u"will be added to those already imported." ), ) folderBoxLine2 = gui.widgetBox( widget=folderBox, box=False, orientation='vertical', ) # Add folder box addfolderBox = gui.widgetBox( widget=folderBoxLine2, box=True, orientation='vertical', ) addfolderBoxLine1 = gui.widgetBox( widget=addfolderBox, orientation='horizontal', ) # Folder path input gui.lineEdit( widget=addfolderBoxLine1, master=self, value='rootFolderPath', orientation='horizontal', label=u'Folder path:', labelWidth=101, callback=self.updateGUI, tooltip=( u"The paths of the folders that will be added to the\n" u"list when button 'Add' is clicked.\n\n" u"Successive paths must be separated with ' / ' \n" u"(whitespace + slash + whitespace). Their order in\n" u"the list will be the same as in this field." ), ) gui.separator(widget=addfolderBoxLine1, width=5) # Button Browse gui.button( widget=addfolderBoxLine1, master=self, label=u'Browse', callback=self.browse, tooltip=( u"Open a dialog for selecting a top folder.\n\n" u"Selected folder paths will appear in the field to\n" u"the left of this button afterwards, ready to be\n" u"added to the list when button 'Add' is clicked." ), ) gui.separator(widget=addfolderBox, width=10) # Filter choice to include only certain files or to exclude files # ------------ # self.applyInclusion = False à mettre dans le init # gui.checkbox() # callback = lambda t=self.applyInclusion : includeLineEdit.setDisabled(not t) # includeLineEdit = gui.lineEdit() # ------------ # Filter box to input include only gui.separator(widget=addfolderBox, width=3) includeBoxLine1 = gui.widgetBox( widget=addfolderBox, box=False, orientation='horizontal', ) # Include only box gui.checkBox( widget=includeBoxLine1, master=self, value='applyInclusion', label=u'Include only', labelWidth=100, callback = lambda: includeLineEdit.setDisabled(not self.applyInclusion), tooltip=( u"Choose the inclusion" ), ) includeLineEdit = gui.lineEdit( widget=includeBoxLine1, master=self, value='inclusionsUser', orientation='horizontal', label=u'', disabled = True, labelWidth=101, tooltip=( u"This field lets you specify a custom filter\n" u"to select the folders to be\n" u"added to the list." ), ) # Filter box to exclude only gui.separator(widget=addfolderBox, width=3) excludeBoxLine1 = gui.widgetBox( widget=addfolderBox, box=False, orientation='horizontal', ) # Exclude only box gui.checkBox( widget=excludeBoxLine1, master=self, value='applyExclusion', label=u'Exclude', labelWidth=100, disabled = False, callback = lambda: includeLineEdit2.setDisabled(not self.applyExclusion), tooltip=( u"Exclude the inclusion" ), ) includeLineEdit2=gui.lineEdit( widget=excludeBoxLine1, master=self, value='exclusionsUser', orientation='horizontal', label=u'', disabled = True, labelWidth=101, tooltip=( u"This field lets you specify a custom filter\n" u"to select the folders to be\n" u"added to the list." ), ) # Sampling box to input the level of sampling gui.separator(widget=addfolderBox, width=3) samplingBoxLine1 = gui.widgetBox( widget=addfolderBox, box=False, orientation='horizontal', ) # Check box for sampling gui.checkBox( widget=samplingBoxLine1, master=self, value='applySampling', label=u'Sampling', labelWidth=100, disabled = False, callback = lambda: samplingSpin.setDisabled(not self.applySampling), tooltip=( u"Choose the sampling level" ), ) # Box to input the level of samplig, spin minv = 10 and maxv = 100 # self.importFilenamesKeyLineEdit = gui.spin( samplingSpin = gui.spin( widget=samplingBoxLine1, master=self, value='samplingRate', minv = 10, maxv = 100, labelWidth=50, orientation='horizontal', tooltip=( u"sampling level" ), ) gui.separator(widget=addfolderBox, width=3) self.addButton = gui.button( widget=addfolderBox, master=self, label=u'Add', callback=self.add, tooltip=( u"Add the folder(s) currently displayed in the\n" u"'folders' text field to the list.\n\n" u"Each of these folders will be associated with the\n" u"specified encoding and annotation (if any).\n\n" u"Other folders may be selected afterwards and\n" u"assigned a different encoding and annotation." ), ) self.advancedSettings.advancedWidgets.append(folderBox) self.advancedSettings.advancedWidgetsAppendSeparator() # Options box... optionsBox = gui.widgetBox( widget=self.controlArea, box=u'Options', orientation='vertical', addSpace=False, ) optionsBoxLine1 = gui.widgetBox( widget=optionsBox, box=False, orientation='horizontal', ) # gui.checkBox( # widget=optionsBoxLine1, # master=self, # value='importFilenames', # label=u'Import folder names with key:', # labelWidth=180, # callback=self.sendButton.settingsChanged, # tooltip=( # u"Import folder names as annotations." # ), # ) # self.importFilenamesKeyLineEdit = gui.lineEdit( # widget=optionsBoxLine1, # master=self, # value='importFilenamesKey', # orientation='horizontal', # callback=self.sendButton.settingsChanged, # tooltip=( # u"Annotation key for importing folder names." # ), # ) gui.separator(widget=optionsBox, width=3) optionsBoxLine2 = gui.widgetBox( widget=optionsBox, box=False, orientation='horizontal', ) gui.checkBox( widget=optionsBoxLine2, master=self, value='autoNumber', label=u'Auto-number with key:', labelWidth=180, callback=self.sendButton.settingsChanged, tooltip=( u"Annotate folders with increasing numeric indices." ), ) self.autoNumberKeyLineEdit = gui.lineEdit( widget=optionsBoxLine2, master=self, value='autoNumberKey', orientation='horizontal', callback=self.sendButton.settingsChanged, tooltip=( u"Annotation key for folder auto-numbering." ), ) gui.separator(widget=optionsBox, width=3) self.advancedSettings.advancedWidgets.append(optionsBox) self.advancedSettings.advancedWidgetsAppendSeparator() gui.rubber(self.controlArea) # Send button... self.sendButton.draw() # Info box... self.infoBox.draw() self.adjustSizeWithTimer() QTimer.singleShot(0, self.sendButton.sendIf)
def __init__(self, parent=None, signalManager=None, name="KEGG Pathways"): OWWidget.__init__(self, parent, signalManager, name, wantGraph=True) self.inputs = [("Examples", Orange.data.Table, self.SetData), ("Reference", Orange.data.Table, self.SetRefData)] self.outputs = [("Selected Examples", Orange.data.Table), ("Unselected Examples", Orange.data.Table)] self.organismIndex = 0 self.geneAttrIndex = 0 self.autoCommit = False self.autoResize = True self.useReference = False self.useAttrNames = 0 self.showOrthology = True self.loadSettings() self.organismCodes = [] self._changedFlag = False self.controlArea.setMaximumWidth(250) box = OWGUI.widgetBox(self.controlArea, "Info") self.infoLabel = OWGUI.widgetLabel(box, "No data on input\n") # Organism selection. box = OWGUI.widgetBox(self.controlArea, "Organism") self.organismComboBox = OWGUI.comboBox( box, self, "organismIndex", items=[], callback=self.Update, addSpace=True, debuggingEnabled=0, tooltip="Select the organism of the input genes") # Selection of genes attribute box = OWGUI.widgetBox(self.controlArea, "Gene attribute") self.geneAttrCandidates = VariableListModel(parent=self) self.geneAttrCombo = OWGUI.comboBox( box, self, "geneAttrIndex", callback=self.Update) self.geneAttrCombo.setModel(self.geneAttrCandidates) OWGUI.checkBox(box, self, "useAttrNames", "Use variable names", disables=[(-1, self.geneAttrCombo)], callback=self.Update) self.geneAttrCombo.setDisabled(bool(self.useAttrNames)) OWGUI.separator(self.controlArea) OWGUI.checkBox(self.controlArea, self, "useReference", "From signal", box="Reference", callback=self.Update) OWGUI.separator(self.controlArea) OWGUI.checkBox(self.controlArea, self, "showOrthology", "Show pathways in full orthology", box="Orthology", callback=self.UpdateListView) OWGUI.checkBox(self.controlArea, self, "autoResize", "Resize to fit", box="Image", callback=self.UpdatePathwayViewTransform) box = OWGUI.widgetBox(self.controlArea, "Cache Control") OWGUI.button(box, self, "Clear cache", callback=self.ClearCache, tooltip="Clear all locally cached KEGG data.") OWGUI.separator(self.controlArea) box = OWGUI.widgetBox(self.controlArea, "Selection") cb = OWGUI.checkBox(box, self, "autoCommit", "Commit on update") button = OWGUI.button(box, self, "Commit", callback=self.Commit, default=True) OWGUI.setStopper(self, button, cb, "_changedFlag", self.Commit) OWGUI.rubber(self.controlArea) spliter = QSplitter(Qt.Vertical, self.mainArea) self.pathwayView = PathwayView(self, spliter) self.pathwayView.scene().selectionChanged.connect( self._onSelectionChanged ) self.mainArea.layout().addWidget(spliter) self.listView = QTreeWidget(spliter) spliter.addWidget(self.listView) self.listView.setAllColumnsShowFocus(1) self.listView.setColumnCount(4) self.listView.setHeaderLabels(["Pathway", "P value", "Genes", "Reference"]) self.listView.setSelectionMode(QTreeWidget.SingleSelection) self.listView.setSortingEnabled(True) self.listView.setMaximumHeight(200) self.connect(self.listView, SIGNAL("itemSelectionChanged()"), self.UpdatePathwayView) self.connect(self.graphButton, SIGNAL("clicked()"), self.saveGraph) select = QAction( "Select All", self, shortcut=QKeySequence.SelectAll ) select.triggered.connect(self.selectAll) self.addAction(select) self.data = None self.refData = None self.resize(800, 600) self.connect(self, SIGNAL("widgetStateChanged(QString, int, QString)"), self.onStateChange) self.has_new_data = False self.has_new_reference_set = False self._executor = ThreadExecutor() self.setEnabled(False) self.setBlocking(True) QTimer.singleShot(0, self._initialize) self.infoLabel.setText("Fetching organism definitions\n")
def __init__(self, files, tab, delete, parent, test=False): """ Keyword arguments: files -- list with dicts containing file names tab -- instanseof AudioVideoTab, ImageTab or DocumentTab indicating currently active tab delete -- boolean that shows if files must removed after conversion parent -- parent widget files: Each dict have only one key and one corresponding value. Key is a file to be converted and it's value is the name of the new file that will be converted. Example list: [{"/foo/bar.png" : "/foo/bar.bmp"}, {"/f/bar2.png" : "/f/bar2.bmp"}] """ super(Progress, self).__init__(parent) self.parent = parent self.files = files self.num_total_files = len(self.files) self.tab = tab self.delete = delete if not test: self._type = tab.name self.step = int(100 / len(files)) self.ok = 0 self.error = 0 self.running = True self.nowQL = QLabel(self.tr('In progress: ')) totalQL = QLabel(self.tr('Total:')) self.nowQPBar = QProgressBar() self.nowQPBar.setValue(0) self.totalQPBar = QProgressBar() self.totalQPBar.setValue(0) self.cancelQPB = QPushButton(self.tr('Cancel')) detailsQPB = QCommandLinkButton(self.tr('Details')) detailsQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) detailsQPB.setCheckable(True) detailsQPB.setMaximumWidth(113) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.outputQTE = QTextEdit() self.outputQTE.setReadOnly(True) self.frame = QFrame() frame_layout = utils.add_to_layout('h', self.outputQTE) self.frame.setLayout(frame_layout) self.frame.hide() hlayout = utils.add_to_layout('h', None, self.nowQL, None) hlayout2 = utils.add_to_layout('h', None, totalQL, None) hlayout3 = utils.add_to_layout('h', detailsQPB, line) hlayout4 = utils.add_to_layout('h', self.frame) hlayout5 = utils.add_to_layout('h', None, self.cancelQPB) vlayout = utils.add_to_layout('v', hlayout, self.nowQPBar, hlayout2, self.totalQPBar, None, hlayout3, hlayout4, hlayout5) self.setLayout(vlayout) detailsQPB.toggled.connect(self.resize_dialog) detailsQPB.toggled.connect(self.frame.setVisible) self.cancelQPB.clicked.connect(self.reject) self.file_converted_signal.connect(self.next_file) self.refr_bars_signal.connect(self.refresh_progress_bars) self.update_text_edit_signal.connect(self.update_text_edit) self.resize(484, 200) self.setWindowTitle('FF Multi Converter - ' + self.tr('Conversion')) if not test: self.get_data() # should be first and not in QTimer.singleShot() QTimer.singleShot(0, self.manage_conversions)
o.changedSlice.connect(updateSlice) o.show() o.resize(600, 600) #f=h5py.File("/home/thorben/phd/src/vtkqt-test/seg.h5") #seg=f['volume/data'][0,:,:,:,0] #f.close() seg = numpy.ones((120, 120, 120), dtype=numpy.uint8) seg[20:40, 20:40, 20:40] = 2 seg[50:70, 50:70, 50:70] = 3 seg[80:100, 80:100, 80:100] = 4 seg[80:100, 80:100, 20:50] = 5 colorTable = [ QColor(255, 0, 0).rgba(), QColor(0, 255, 0).rgba(), QColor(255, 255, 0).rgba(), QColor(255, 0, 255).rgba(), QColor(0, 0, 255).rgba(), QColor(128, 0, 128).rgba() ] o.SetColorTable(colorTable) QTimer.singleShot( 0, partial(o.DisplayObjectMeshes, seg, suppressLabels=(1, ))) app.exec_() # [vtkusers] Depth peeling not used, but I can't see why. # http://public.kitware.com/pipermail/vtkusers/2010-August/111040.html