def resetGUI(self): QApplication.restoreOverrideCursor() self.lblProgress.setText('') self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.btnRun.setEnabled(True) self.btnClose.setEnabled(True)
class TestIconLoader(unittest.TestCase): def setUp(self): from PyQt4.QtGui import QApplication self.app = QApplication([]) def tearDown(self): self.app.exit() del self.app def test_loader(self): loader = icon_loader() self.assertEqual(loader.search_paths(), DEFAULT_SEARCH_PATHS) icon = loader.get("icons/CanvasIcon.png") self.assertTrue(not icon.isNull()) path = loader.find(":icons/CanvasIcon.png") self.assertTrue(os.path.isfile(path)) icon = loader.get(":icons/CanvasIcon.png") self.assertTrue(not icon.isNull()) def test_from_desc(self): from .registry.description import ( WidgetDescription, CategoryDescription ) desc = WidgetDescription.from_module( "Orange.OrangeWidgets.Data.OWFile" ) loader = icon_loader.from_description(desc) path = loader.find(desc.icon) self.assertTrue(os.path.isfile(path)) icon = loader.get(desc.icon) self.assertTrue(not icon.isNull()) desc = CategoryDescription.from_package("Orange.OrangeWidgets.Data") loader = icon_loader.from_description(desc) path = loader.find("icons/file.svg") self.assertTrue(os.path.isfile(path)) icon = loader.get("icons/file.svg") self.assertTrue(not icon.isNull()) def test_package_reflection(self): from Orange.OrangeWidgets.Data import OWFile from Orange.OrangeWidgets import Data package_name = Data.__name__ p1 = package("Orange.OrangeWidgets.Data.OWFile.OWFile") self.assertEqual(p1, package_name) p2 = package("Orange.OrangeWidgets.Data.OWFile") self.assertEqual(p2, package_name) p3 = package("Orange.OrangeWidgets.Data") self.assertEqual(p3, package_name) p4 = package(OWFile.__name__) self.assertEqual(p4, package_name) dirname = package_dirname(package_name) self.assertEqual(dirname, os.path.dirname(Data.__file__))
def searchId(self, id, stype): QApplication.setOverrideCursor(Qt.WaitCursor) title_field = 'name' if stype == 'movie': cap = CapCinema title_field = 'original_title' elif stype == 'person': cap = CapCinema elif stype == 'torrent': cap = CapTorrent elif stype == 'subtitle': cap = CapSubtitle if '@' in id: backend_name = id.split('@')[1] id = id.split('@')[0] else: backend_name = None for backend in self.weboob.iter_backends(): if backend.has_caps(cap) and ((backend_name and backend.name == backend_name) or not backend_name): exec('object = backend.get_%s(id)' % (stype)) if object: func_display = 'self.display' + stype[0].upper() + stype[1:] exec("self.doAction('Details of %s \"%%s\"' %% object.%s, %s, [object, backend])" % (stype, title_field, func_display)) QApplication.restoreOverrideCursor()
def __init__(self, parent = None): ''' Constructor ''' super(raceSelector, self).__init__(parent) if _DETAILS.dateList is None: QApplication.setOverrideCursor(Qt.WaitCursor) _DETAILS.dateList = Download.RPDownloader.getAvailableDates() QApplication.setOverrideCursor(Qt.ArrowCursor) self.setupUi(self) self.populateDates() if _DETAILS.selectedDate is not None: try: index = _DETAILS.dateList.index(_DETAILS.selectedDate) except ValueError: return self.dateList.setCurrentRow(index) if _DETAILS.selectedMeeting is not None: try: index = _DETAILS.meetings.index(_DETAILS.selectedMeeting) except ValueError: return self.courseList.setCurrentRow(index) self.race = None self.connect(self, SIGNAL("accepted()"), self.on_raceSelector_accepted)
def __init__(self, *args): QApplication.__init__(self, *args) styleName = str(self.style().metaObject().className())[1:-5].lower() if styleName not in ("windowsxp", "windowsvista", "mac"): self.setPalette(self.style().standardPalette()) self.setWindowIcon(QIcon(":/icon_app.svg")) self.connect(self, SIGNAL("lastWindowClosed()"), NodeBoxDocumentBaseClass.writeSettings)
def main(): app = QApplication(sys.argv) widget = QWidget() QPixmap.grabWidget(widget, 100, 100, 200, 200) widget.show() app.exec_() e = Event() e.capture = False e.daemon = False e.start() while True: if e.is_press and e.is_release: if e.press_cnt == 1: if e.start_x > e.end_x: e.start_x, e.end_x = e.end_x, e.start_x if e.start_y > e.end_y: e.start_y, e.end_y = e.end_y, e.start_y width = e.end_x - e.start_x height = e.end_y - e.start_y f = tempfile.NamedTemporaryFile( prefix='screentshot_', suffix='.png') command = "import -window root -crop '%sx%s+%s+%s' " %( width, height, e.start_x, e.start_y) command += f.name EasyProcess(command).call() im = Image.open(f.name) im.show() break e.stop()
def testQuery(self): self.ui.bar.clearWidgets() self.ui.bar.pushMessage("Info", QApplication.translate('CartoDBPlugin', 'Validating Query'), level=QgsMessageBar.INFO) sql = self.ui.sqlEditor.text() if sql is None or sql == '': self.ui.bar.clearWidgets() self.ui.bar.pushMessage("Warning", "Please write the sql query", level=QgsMessageBar.WARNING, duration=5) self.setValidQuery(False) return sql = 'SELECT count(cartodb_id) num, ST_Union(the_geom) the_geom FROM (' + sql + ') a' cartoUrl = 'http://{}.cartodb.com/api/v2/sql?format=GeoJSON&q={}&api_key={}'.format(self.currentUser, sql, self.currentApiKey) response = urlopen(cartoUrl) result = json.loads(response.read()) self.ui.bar.clearWidgets() if 'error' not in result: self.ui.bar.pushMessage("Info", QApplication.translate('CartoDBPlugin', 'Query is valid'), level=QgsMessageBar.INFO, duration=5) self.setValidQuery(True) else: if 'hint' in result: self.ui.bar.pushMessage("Warning", result['hint'], level=QgsMessageBar.WARNING, duration=10) for error in result['error']: self.ui.bar.pushMessage("Error", error, level=QgsMessageBar.CRITICAL, duration=5) self.setValidQuery(False)
def setData(self, index, value, role): if role != Qt.EditRole or index.column() != 0: return False item = index.internalPointer() new_value = unicode(value) if isinstance(item, SchemaItem) or isinstance(item, TableItem): obj = item.getItemData() # rename schema or table or view if new_value == obj.name: return False QApplication.setOverrideCursor(Qt.WaitCursor) try: obj.rename(new_value) self._onDataChanged(index) except BaseError as e: DlgDbError.showError(e, self.treeView) return False finally: QApplication.restoreOverrideCursor() return True return False
def __init__(self): QApplication.__init__(self,[]) self.mainw=uic.loadUi(initpath+"main.ui")#l.loadUi(f,None) self.pushbutton_go=self.mainw.findChild(QPushButton,"pushButton_go") QApplication.connect(self.pushbutton_go,SIGNAL('clicked()'),self.handlego) self.pushButton_pdf=self.mainw.findChild(QPushButton,"pushButton_pdf") QApplication.connect(self.pushButton_pdf,SIGNAL('clicked()'),self.handlepdf) self.pushButton_rtf=self.mainw.findChild(QPushButton,"pushButton_rtf") QApplication.connect(self.pushButton_rtf,SIGNAL('clicked()'),self.handlertf) self.pushButton_excel=self.mainw.findChild(QPushButton,"pushButton_excel") QApplication.connect(self.pushButton_excel,SIGNAL('clicked()'),self.handleexcel) self.grid1=self.mainw.findChild(QTableWidget,"tableWidget") self.web1=self.mainw.findChild(QWebView,"webView") self.loadData() self.actionOpen_sample=self.mainw.findChild(QAction,"actionOpen_sample") self.connect(self.actionOpen_sample,SIGNAL('triggered (bool)'),self.OnOpenSample) self.actionClear_all=self.mainw.findChild(QAction,"actionClear_all") self.connect(self.actionClear_all,SIGNAL('triggered (bool)'),self.ClearAll) self.actionExit=self.mainw.findChild(QAction,"actionExit") self.connect(self.actionExit,SIGNAL('triggered (bool)'),self.OnExit)
def hasChildren(self, index): QApplication.setOverrideCursor(Qt.WaitCursor) if index.isValid(): item = self.itemFromIndex(index) path = item.path if item.hasChildren(): children = True elif item.isClass or item.isFunction: children = False elif isdir(path): paths = [join(path, p) for p in listdir(path)] paths = [p for p in paths if isPackage(p) or isSource(p)] paths.sort() for key, subiter in groupby(paths, lambda x:splitext(x)[0]): pth = sorted(subiter)[0] item.appendRow(SysPathItem(pth, split(pth)[1])) children = bool(paths) elif splitext(path)[1] in pyexts: contents = readModule(self.dottedName(item), split(path)[0]) for name, obj in sorted(contents.items()): item.appendRow(SysPathItem(path, name, obj)) children = bool(contents) else: children = False else: children = True QApplication.restoreOverrideCursor() return children
def main(): import sip from PyQt4.QtGui import QApplication from Orange.classification import logistic_regression, svm from Orange.evaluation import testing app = QApplication([]) w = OWLiftCurve() w.show() w.raise_() data = Orange.data.Table("ionosphere") results = testing.CrossValidation( data, [logistic_regression.LogisticRegressionLearner(penalty="l2"), logistic_regression.LogisticRegressionLearner(penalty="l1"), svm.SVMLearner(probability=True), svm.NuSVMLearner(probability=True) ], store_data=True ) results.fitter_names = ["LR l2", "LR l1", "SVM", "Nu SVM"] w.set_results(results) rval = app.exec_() sip.delete(w) del w app.processEvents() del app return rval
def __init__(self, argv): """ Constructor @load a config dictionnary """ QApplication.__init__(self, argv) self.settings=QSettings() #for e in self.settings.allKeys(): # print str(e) self.connect(self, SIGNAL('lastWindowClosed()'), self.goodbye) self.undoStack = QUndoStack(self) self.useGL = self.checkGL() self.lowMemory = False self.multiCore = False #self.modelView = 'Samples View' #self.showSplash=self.settings.value('showSplash', True).toBool() from gui.MetBaseGui import MSSplashScreen self.splash = MSSplashScreen(QPixmap(path.normcase("gui/icons/Tux-G2.png")), Qt.WindowStaysOnTopHint) self.splash.show() #self.splash.setMask(pixmap.mask()) self.splash.showMessage((u'Starting now...'), Qt.AlignCenter | Qt.AlignBottom, Qt.black) self.processEvents() self.controllers = {} self.metmsconfig=self.loadConfiguration()
class QMainLoopSrc(gobject.Source): """ A GSource to add to a mainloop. Use in place of a QApplication or gobject.MainLoop. This shoud be optimized in check and prepare to be usable. """ def __init__(self, args=sys.argv): gobject.Source.__init__(self) self.qapp = QApplication(args) self.loop = gobject.MainLoop() self.attach(self.loop.get_context()) self.run = self.loop.run def quit(self): self.qapp.quit() self.loop.quit() def prepare(self): """ """ # ugg just keep checking return (-1, True) def check(self): """ maybe add an idle call via QTimer.start(0) just before the event to see if it is idle, the return False? """ return True def dispatch(self, *args): try: self.qapp.processEvents(QEventLoop.AllEvents) except KeyboardInterrupt, e: pass return True
def run(): parser = ArgumentParser(description='Scrabble game including an AI.') parser.add_argument('players', metavar='PLAYER', type=str, nargs='+', help='A player like "TYPE:NAME", valid types are:' + ' bot, human') parser.add_argument('-r', '--rows', type=int, default=11, dest='rows', help='Board rows (default: 11)') parser.add_argument('-c', '--columns', type=int, default=11, dest='columns', help='Board columns (default: 11)') parser.add_argument('-s', '--rack', type=int, default=7, dest='rack', help='Rack size (default: 7)') parser.add_argument('-w', '--words', type=str, default=DEFAULT_WORDLIST, dest='words', help='Bot words file (default: %s)' % DEFAULT_WORDLIST) parser.add_argument('-l', '--letters', type=str, default=DEFAULT_LETTERSET, dest='letters', help='Letter-set file (default: %s)' % DEFAULT_LETTERSET) args = parser.parse_args() game = Game(args.rows, args.columns, args.rack, args.letters) for player in args.players: typ,name = player.split(':') game.add_player(BruteForceBot(name, game, words=args.words) if typ.lower() == 'bot' else Human(name, game)) app = QApplication(argv) win = Window(game) app.exec_()
def cleanUp(self): QApplication.processEvents() for scene in self._imageViews: scene.close() scene.deleteLater() self._imageViews = [] QApplication.processEvents()
def run_ninja(): """First obtain the execution args and create the resources folder.""" signal.signal(signal.SIGINT, signal.SIG_DFL) # Change the process name only for linux yet if not settings.IS_WINDOWS and not settings.IS_MAC_OS: try: import ctypes libc = ctypes.CDLL('libc.so.6') #Set the application name procname = 'ninja-ide' libc.prctl(15, '%s\0' % procname, 0, 0, 0) except: print("The process couldn't be renamed'") filenames, projects_path, extra_plugins, linenos, log_level, log_file = \ cliparser.parse() resources.create_home_dir_structure() # Load Logger from ninja_ide.tools.logger import NinjaLogger NinjaLogger.argparse(log_level, log_file) # Load Settings settings.load_settings() # Start the UI app = QApplication(sys.argv) from ninja_ide import gui gui.start_ide(app, filenames, projects_path, extra_plugins, linenos) sys.exit(app.exec_())
def test_main(argv=None): import sys if argv is None: argv = sys.argv argv = list(argv) a = QApplication(argv) if len(argv) > 1: filename = argv[1] else: filename = "iris" ow = OWScatterPlot() ow.show() ow.raise_() data = Orange.data.Table(filename) ow.set_data(data) ow.set_subset_data(data[:30]) ow.handleNewSignals() rval = a.exec() ow.set_data(None) ow.set_subset_data(None) ow.handleNewSignals() ow.saveSettings() ow.onDeleteWidget() return rval
def createTmpBase64(rLayer): try: # tmpFile = tempfile.NamedTemporaryFile(prefix="base64", delete=False) # infile = open(unicode(rLayer.source())) # tmpFileName = tmpFile.name # outfile = open(tmpFileName, 'w') # base64.encode(infile,outfile) # outfile.close() # outfile = open(tmpFileName, 'r') # base64String = outfile.read() # outfile.close() # os.remove(tmpFile.name) tmpFile = tempfile.NamedTemporaryFile(prefix="base64", delete=False) infile = open(rLayer.source()) tmpFileName = tmpFile.name outfile = tmpFile #open(tmpFileName, 'w') base64.encode(infile,outfile) outfile.close() infile.close() outfile = open(tmpFileName, 'r') base64String = outfile.read() outfile.close() os.remove(tmpFileName) except: QMessageBox.critical(None, QApplication.translate("QgsWps","Error"), QApplication.translate("QgsWps","Unable to create temporal file: ") + filename + QApplication.translate("QgsWps"," for base64 encoding") ) return base64String
def executeSql(self): sql = self._getSqlQuery() if sql == "": return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # delete the old model old_model = self.viewResult.model() self.viewResult.setModel(None) if old_model: old_model.deleteLater() self.uniqueCombo.clear() self.geomCombo.clear() try: # set the new model model = self.db.sqlResultModel(sql, self) self.viewResult.setModel(model) self.lblResult.setText(self.tr("%d rows, %.1f seconds") % (model.affectedRows(), model.secs())) except BaseError, e: QApplication.restoreOverrideCursor() DlgDbError.showError(e, self) return
def configuration(self): #Return chart configuration settings config = None curr_editor = self.series_type_container.currentWidget() if not curr_editor is None: try: config = curr_editor.configuration() except AttributeError: raise AttributeError(QApplication.translate("ComposerChartConfigEditor", "Series editor does not contain a method for " "returning a ChartConfigurationSettings object.")) else: raise Exception(QApplication.translate("ComposerChartConfigEditor", "No series editor found.")) if not config is None: ref_table_config = self.ref_table.properties() config.extract_from_linked_table_properties(ref_table_config) config.set_insert_legend(self.gb_legend.isChecked()) config.set_title(self.txt_plot_title.text()) config.set_legend_position(self.cbo_legend_pos.itemData (self.cbo_legend_pos.currentIndex())) return config
def set_configuration(self, configuration): #Load configuration settings short_name = configuration.plot_type if short_name: if short_name in self._short_name_idx: plot_type_idx = self._short_name_idx[short_name] self.cbo_chart_type.setCurrentIndex(plot_type_idx) #Set linked table properties self.ref_table.set_properties(configuration.linked_table_props()) #Set series editor properties curr_editor = self.series_type_container.currentWidget() if not curr_editor is None: try: curr_editor.set_configuration(configuration) self._set_graph_properties(configuration) except AttributeError: msg = QApplication.translate("ComposerChartConfigEditor", "Configuration could not be set for series editor.") self._notif_bar.clear() self._notif_bar.insertErrorNotification(msg) else: msg = QApplication.translate("ComposerChartConfigEditor", "Configuration failed to load. Plot type cannot be determined.") self._notif_bar.clear() self._notif_bar.insertErrorNotification(msg)
def main(): app = QApplication(sys.argv) editor = pyqode.core.QGenericCodeEdit() editor.show() # show the api pyqode is currently using editor.setPlainText("pyQode using %s " % os.environ["QT_API"]) app.exec_()
def loadDcmDir(self): self.statusBar().showMessage('Reading DICOM directory...') QApplication.processEvents() # oseg = self.oseg # if oseg.datapath is None: # oseg.datapath = dcmreader.get_dcmdir_qt(app=True) self.datapath = dcmreader.get_dcmdir_qt(app=True) # if oseg.datapath is None: # self.statusBar().showMessage('No DICOM directory specified!') # return if self.datapath is None: self.statusBar().showMessage('No DICOM directory specified!') return reader = datareader.DataReader() # oseg.data3d, oseg.metadata = reader.Get3DData(oseg.datapath) self.data3d, self.metadata = reader.Get3DData(self.datapath) # oseg.process_dicom_data() self.process_dicom_data() # self.setLabelText(self.text_dcm_dir, oseg.datapath) self.setLabelText(self.text_dcm_dir, self.datapath) self.setLabelText(self.text_dcm_data, self.getDcmInfo()) self.statusBar().showMessage('Ready')
def treeLoaded(self, reply): """ update the tree of scripts/models whenever HTTP request is finished """ QApplication.restoreOverrideCursor() if reply.error() != QNetworkReply.NoError: self.popupError(reply.error(), reply.request().url().toString()) else: resources = unicode(reply.readAll()).splitlines() resources = [r.split(',') for r in resources] self.resources = {f: (v, n) for f, v, n in resources} for filename, version, name in sorted(resources, key=lambda kv: kv[2].lower()): treeBranch = self.getTreeBranchForState(filename, float(version)) item = TreeItem(filename, name, self.icon) treeBranch.addChild(item) if treeBranch != self.notinstalledItem: item.setCheckState(0, Qt.Checked) reply.deleteLater() self.tree.addTopLevelItem(self.toupdateItem) self.tree.addTopLevelItem(self.notinstalledItem) self.tree.addTopLevelItem(self.uptodateItem) self.webView.setHtml(self.HELP_TEXT)
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowFlags(Qt.Window) self._mdi_area = QMdiArea() self._mdi_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self._mdi_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setCentralWidget(self._mdi_area) # set the size of mid_area and DocumentViewManager based on the # screen size. screen = QDesktopWidget().availableGeometry() self._mdi_area.resize(screen.width() - 30, screen.height() - 80) self.resize(self._mdi_area.size()) self._mdi_area.subWindowActivated.connect(self.update_actions) self._viewer_mapper = QSignalMapper(self) self._viewer_mapper.mapped[QWidget].connect(self.set_active_sub_window) win_title = QApplication.translate( "DocumentViewManager", "Document Viewer" ) self.setWindowTitle(win_title) self.setUnifiedTitleAndToolBarOnMac(True) self.statusBar().showMessage( QApplication.translate( "DocumentViewManager", "Ready" ) ) self._doc_viewers = {} self._create_menu_actions() self.update_actions()
def doSaveAutoField( self, layer, fieldName, expression ): """ Repetitive logic to save or overwrite an AutoField """ # Check if the field is an AutoField and ask if we should overwrite it res = True bCalculateOnExisting = self.chkCalculateOnExisting.isChecked() if self.autoFieldManager.isFieldAnAutoField( layer, fieldName ): reply = QMessageBox.question( self.iface.mainWindow(), QApplication.translate( "AutoFieldsDockWidgetPy", "Confirmation" ), QApplication.translate( "AutoFieldsDockWidgetPy", "The field '" ) + \ fieldName + QApplication.translate( "AutoFieldsDockWidgetPy", "' from layer '" ) + layer.name() + \ QApplication.translate( "AutoFieldsDockWidgetPy", "' is already an AutoField.\nDo you want to overwrite it?" ), QMessageBox.Yes | QMessageBox.No, QMessageBox.No ) if reply == QMessageBox.Yes: res = self.autoFieldManager.overwriteAutoField( layer, fieldName, expression, calculateOnExisting=bCalculateOnExisting ) else: res = self.autoFieldManager.createAutoField( layer, fieldName, expression, calculateOnExisting=bCalculateOnExisting ) if not res: # res will only be False if create/overwriteAutoField return False self.msg.show( "[Error] The AutoField for layer '" + layer.name() + \ "' and field '" + fieldName + "' couldn't be created.", 'warning', True )
def main(): #func to call config wizz app0 = QApplication(sys.argv) ldsc = LDSConfigWizard() ldsc.show() sys.exit(app0.exec_())
def _set_settings(self, settings): old_settings = self.__dict__.get('settings', None) if settings == old_settings: return self.__dict__['settings'] = settings if self.thread.isRunning(): QApplication.postEvent(self, RFBConfigureClientEvent())
def __init__(self, formula, smiles=None, alphabet=MSAlphabet.withElements(['C','H','N','O','P','S'])): #change the formula(string) to object dict dict.__init__(self) self.alphabet = alphabet #alphabet of the formula (used symbol) reg = re.compile('([A-Z]|[A-Z][a-z])(\d+)') if '.' in formula: for splitted in formula.split('.')[:-1]: if reg.match(splitted): for element in self.alphabet: if element.symbol == reg.match(splitted).group(1): self[element] = int(reg.match(splitted).group(2)) break else: try: from PyQt4.QtGui import QApplication QApplication.instance().view.showErrorMessage('Error', "Unknown error: formula is obviously not good...") except ImportError: raise ValueError, "Unknown error: formula is obviously not good..." else: try: from PyQt4.QtGui import QApplication QApplication.instance().view.showErrorMessage('Error', "MSFormula Object must contain '.' to separate the different elements") except ImportError: raise ValueError, "MSFormula Object must contain '.' to separate the different elements" self.mass=None #mass of the formula self.smiles=smiles #smiles formula self.score=None #score self.compounds=[] #will ba list of string (name) self.peaksGroup=None
def main(): """Start GUI """ app = QApplication([]) window = MainWindow() window.show() app.exec_()
return self.stop def reset_stop(self): """Reset the stop toggle so that the event loop can run.""" self.stop = False def close(self, args=None): """Stop the event loop safely, ensuring that the sockets are closed. Once the thread has stopped, reset the stop toggle so that it doesn't block the thread starting again the next time.""" remove_slot(self.finished, self.reset_stop) self.stop = True if __name__ == "__main__": import sys app = QApplication.instance() standalone = app is None # false if there is already an app instance if standalone: # if there isn't an instance, make one app = QApplication(sys.argv) try: from PyQt4.QtGui import QWidget except ImportError: from PyQt5.QtWidgets import QWidget ps = PyServer() ps.textin.connect(print) ps.add_message('24', 'Hello world!') remove_slot(ps.dxnum, ps.close, True) # close server after message ps.start() # will keep running until you call ps.close() w = QWidget()
tmp = [ line.find("#L") for line in txt] itmp = np.where(np.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ","").split(" ") print("data labels: ",labels) # # build and send orange table # domain = Domain([ ContinuousVariable(i) for i in labels ]) table = Table.from_numpy(domain, out) self.send("xoppy_table",table) def defaults(self): self.resetSettings() self.compute() return def help1(self): print("help pressed.") xoppy_doc('undulator_power_density') if __name__ == "__main__": app = QApplication(sys.argv) w = OWundulator_power_density() w.show() app.exec() w.saveSettings()
def main(): """Main function""" app = QApplication([]) name_parameter = StringParameter('UUID-1') name_parameter.name = 'Resource name' name_parameter.help_text = ( 'Name of the resource that will be provided as part of minimum needs.' 'e.g. Tea, Water etc.') name_parameter.description = ( 'A <b>resource</b> is something that you provide to displaced persons ' 'in the event of a disaster. The resource will be made available ' 'at IDP camps and may need to be stockpiled by contingency planners ' 'in their preparations for a disaster.') name_parameter.is_required = True name_parameter.value = '' description_parameter = StringParameter('UUID-1') description_parameter.name = 'Resource description' description_parameter.help_text = ( 'Description of the resource that will be provided as part of minimum ' 'needs. e.g. Tea, Water etc.') description_parameter.description = ( 'Description of the resource that will be provided as part of minimum ' 'needs. e.g. Tea, Water etc.') description_parameter.is_required = True description_parameter.value = '' unit_parameter = StringParameter('UUID-2') unit_parameter.name = 'Units' unit_parameter.help_text = ('Unit for the resources. e.g. litres, kg etc.') unit_parameter.description = ( 'A <b>unit</b> the basic measurement unit used for computing the ' 'allowance per individual. For example when planning water rations ' 'the units would be litres.') unit_parameter.is_required = True unit_parameter.value = '' minimum_parameter = FloatParameter('UUID-3') minimum_parameter.name = 'Minimum allowed' minimum_parameter.is_required = True minimum_parameter.precision = 3 minimum_parameter.minimum_allowed_value = -99999.0 minimum_parameter.maximum_allowed_value = 99999.0 minimum_parameter.help_text = 'The minimum allowable quantity per person. ' minimum_parameter.description = ( 'The <b>minimum</b> is the minimum allowed quantity of the resource ' 'per person. For example you may dictate that the water ration per ' 'person per day should never be allowed to be less than 0.5l.') minimum_parameter.value = 1.0 maximum_parameter = FloatParameter('UUID-3') maximum_parameter.name = 'Minimum allowed' maximum_parameter.is_required = True maximum_parameter.precision = 3 maximum_parameter.minimum_allowed_value = -99999.0 maximum_parameter.maximum_allowed_value = 99999.0 maximum_parameter.help_text = 'The maximum allowable quantity per person. ' maximum_parameter.description = ( 'The <b>maximum</b> is the maximum allowed quantity of the resource ' 'per person. For example you may dictate that the water ration per ' 'person per day should never be allowed to be more than 50l.') maximum_parameter.value = 1.0 maximum_parameter = FloatParameter('UUID-4') maximum_parameter.name = 'Minimum allowed' maximum_parameter.is_required = True maximum_parameter.precision = 3 maximum_parameter.minimum_allowed_value = -99999.0 maximum_parameter.maximum_allowed_value = 99999.0 maximum_parameter.help_text = 'The maximum allowable quantity per person. ' maximum_parameter.description = ( 'The <b>maximum</b> is the maximum allowed quantity of the resource ' 'per person. For example you may dictate that the water ration per ' 'person per day should never be allowed to be more than 50l.') maximum_parameter.value = 1.0 default_parameter = FloatParameter('UUID-5') default_parameter.name = 'Default' default_parameter.is_required = True default_parameter.precision = 3 default_parameter.minimum_allowed_value = -99999.0 default_parameter.default_allowed_value = 99999.0 default_parameter.help_text = 'The default allowable quantity per person. ' default_parameter.description = ( 'The <b>default</b> is the default allowed quantity of the resource ' 'per person. For example you may indicate that the water ration per ' 'person per day should be 25l.') default_parameter.value = 1.0 parameters = [ name_parameter, description_parameter, unit_parameter, minimum_parameter, maximum_parameter, default_parameter ] parameter_container = ParameterContainer(parameters) widget = QWidget() layout = QGridLayout() layout.addWidget(parameter_container) widget.setLayout(layout) widget.setGeometry(0, 0, 500, 500) widget.show() new_parameters = parameter_container.get_parameters() for new_parameter in new_parameters: print new_parameter.name, new_parameter.value sys.exit(app.exec_())
item = QtGui.QTableWidgetItem(s) #item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable) item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) item.setWhatsThis("You can change this task's comment, start time and end time."); self.setItem(irow,icol,item); con.close() self.setRowCount(irow) # Sorting columns for col in range(ncols): self.resizeColumnToContents(col) self.setCurrentItem(self.item(0,0)) #=============================================================================== # Example #=============================================================================== if __name__ == '__main__': import sys from PyQt4.QtGui import QMainWindow, QApplication class ApplicationWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.tblwidget = QueryTableWidget(self) self.tblwidget.setFocus() self.setCentralWidget(self.tblwidget) app = QApplication(sys.argv) win = ApplicationWindow() win.show() sys.exit(app.exec_())
def main(args): app = QApplication(args) win = ChatTracer() app.lastWindowClosed.connect(win.closeApp) return app.exec_()
def _translate(context, text, disambig): return QApplication.translate(context, text, disambig)
def startGui(): app = QApplication(sys.argv) form = Form() form.show() app.exec_()
def close_busy_dlg(*args): QApplication.postEvent(busy_dlg, QCloseEvent())
def runAction(self, action): action = unicode(action) if action.startswith("rows/"): if action == "rows/count": self.refreshRowCount() return True elif action.startswith("triggers/"): parts = action.split('/') trigger_action = parts[1] msg = QApplication.translate( "DBManagerPlugin", "Do you want to %s all triggers?") % trigger_action QApplication.restoreOverrideCursor() try: if QMessageBox.question( None, QApplication.translate("DBManagerPlugin", "Table triggers"), msg, QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: return False finally: QApplication.setOverrideCursor(Qt.WaitCursor) if trigger_action == "enable" or trigger_action == "disable": enable = trigger_action == "enable" self.aboutToChange() self.database().connector.enableAllTableTriggers( enable, (self.schemaName(), self.name)) self.refreshTriggers() return True elif action.startswith("trigger/"): parts = action.split('/') trigger_name = parts[1] trigger_action = parts[2] msg = QApplication.translate("DBManagerPlugin", "Do you want to %s trigger %s?") % ( trigger_action, trigger_name) QApplication.restoreOverrideCursor() try: if QMessageBox.question( None, QApplication.translate("DBManagerPlugin", "Table trigger"), msg, QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: return False finally: QApplication.setOverrideCursor(Qt.WaitCursor) if trigger_action == "delete": self.aboutToChange() self.database().connector.deleteTableTrigger( trigger_name, (self.schemaName(), self.name)) self.refreshTriggers() return True elif trigger_action == "enable" or trigger_action == "disable": enable = trigger_action == "enable" self.aboutToChange() self.database().connector.enableTableTrigger( trigger_name, enable, (self.schemaName(), self.name)) self.refreshTriggers() return True return False
import os import sys if len(sys.argv) > 1 and sys.argv[1] == '4' or os.environ.get( 'QT_SELECT') == '4': from PyQt4.QtGui import QApplication, QKeySequence from PyQt4.QxtGlobalShortcut import QxtGlobalShortcut else: from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QKeySequence from PyQt5.QxtGlobalShortcut import QxtGlobalShortcut SHORTCUT_SHOW = "Ctrl+Alt+G" # Ctrl maps to Command on Mac OS X SHORTCUT_EXIT = "Ctrl+Alt+Q" # again, Ctrl maps to Command on Mac OS X app = QApplication([]) shortcut_show = QxtGlobalShortcut() shortcut_show.setShortcut(QKeySequence(SHORTCUT_SHOW)) shortcut_show.activated.connect(lambda: print("Shortcut Activated!")) shortcut_exit = QxtGlobalShortcut() shortcut_exit.setShortcut(QKeySequence(SHORTCUT_EXIT)) shortcut_exit.activated.connect(app.exit) print('Global show shortcut: {}'.format(SHORTCUT_SHOW)) print('Global exit shortcut: {}'.format(SHORTCUT_EXIT)) return_code = app.exec_() del shortcut_show
if not utils.canEnterGUIMode4(): log.error( "%s requires GUI support (try running with --qt3). Exiting." % __mod__) sys.exit(1) if ui_toolkit == 'qt3': try: from qt import * from ui.printerform import PrinterForm except ImportError: log.error("Unable to load Qt3 support. Is it installed?") sys.exit(1) # create the main application object app = QApplication(sys.argv) if loc is None: loc = user_conf.get('ui', 'loc', 'system') if loc.lower() == 'system': loc = str(QTextCodec.locale()) log.debug("Using system locale: %s" % loc) if loc.lower() != 'c': e = 'utf8' try: l, x = loc.split('.') loc = '.'.join([l, e]) except ValueError: l = loc loc = '.'.join([loc, e])
args.win_size = int( args.win_size / 4.0) * 4 # make sure the width of the image can be divided by 4 # initialize the colorization model colorModel = CI.ColorizeImageCaffe(Xd=args.load_size) colorModel.prep_net(args.gpu, args.color_prototxt, args.color_caffemodel) if (args.no_dist): distModel = None else: distModel = CI.ColorizeImageCaffeDist(Xd=args.load_size) distModel.prep_net(args.gpu, args.dist_prototxt, args.dist_caffemodel) # initialize application app = QApplication(sys.argv) window = gui_design.GUIDesign(color_model=colorModel, dist_model=distModel, img_file=args.image_file, load_size=args.load_size, win_size=args.win_size, user_study=args.user_study, ui_time=args.ui_time) app.setStyleSheet(qdarkstyle.load_stylesheet( pyside=False)) # comment this if you do not like dark stylesheet app.setWindowIcon(QIcon('imgs/logo.png')) # load logo window.setWindowTitle('iColor') window.setWindowFlags(window.windowFlags() & ~Qt.WindowMaximizeButtonHint) # fix window siz window.show() app.exec_()
def main(): """Main function to run the example.""" app = QApplication([]) options = OrderedDict([ (DO_NOT_REPORT, { 'label': 'Do not report', 'value': None, 'type': STATIC, 'constraint': {} }), (GLOBAL_DEFAULT, { 'label': 'Global default', 'value': 0.5, 'type': STATIC, 'constraint': {} }), ( CUSTOM_VALUE, { 'label': 'Custom', 'value': 0.7, # Taken from keywords / recent value 'type': SINGLE_DYNAMIC, 'constraint': { 'min': 0, 'max': 1 } }), ( FIELDS, { 'label': 'Ratio fields', 'value': ['field A', 'field B', 'field C'], # Taken from keywords 'type': MULTIPLE_DYNAMIC, 'constraint': {} }) ]) default_value_parameter = GroupSelectParameter() default_value_parameter.name = 'Group Select parameter' default_value_parameter.help_text = 'Help text' default_value_parameter.description = 'Description' default_value_parameter.options = options default_value_parameter.selected = 'ratio fields' parameters = [default_value_parameter] extra_parameters = [(GroupSelectParameter, GroupSelectParameterWidget)] parameter_container = ParameterContainer(parameters, extra_parameters=extra_parameters) parameter_container.setup_ui() widget = QWidget() layout = QGridLayout() layout.addWidget(parameter_container) widget.setLayout(layout) widget.setGeometry(0, 0, 500, 500) widget.show() sys.exit(app.exec_())
def registerDatabaseActions(self, mainWindow): action = QAction( QApplication.translate("DBManagerPlugin", "&Re-connect"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Database"), self.reconnectActionSlot) if self.schemas() is not None: action = QAction( QApplication.translate("DBManagerPlugin", "&Create schema"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.createSchemaActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "&Delete (empty) schema"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.deleteSchemaActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "Delete selected item"), self) mainWindow.registerAction(action, None, self.deleteActionSlot) action.setShortcuts(QKeySequence.Delete) action = QAction( QIcon(":/db_manager/actions/create_table"), QApplication.translate("DBManagerPlugin", "&Create table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.createTableActionSlot) action = QAction( QIcon(":/db_manager/actions/edit_table"), QApplication.translate("DBManagerPlugin", "&Edit table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.editTableActionSlot) action = QAction( QIcon(":/db_manager/actions/del_table"), QApplication.translate("DBManagerPlugin", "&Delete table/view"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.deleteTableActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "&Empty table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.emptyTableActionSlot) if self.schemas() is not None: action = QAction( QApplication.translate("DBManagerPlugin", "&Move to schema"), self) action.setMenu(QMenu(mainWindow)) invoke_callback = lambda: mainWindow.invokeCallback( self.prepareMenuMoveTableToSchemaActionSlot) QObject.connect(action.menu(), SIGNAL("aboutToShow()"), invoke_callback) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"))
# 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, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self.on_page_load) self.mainFrame().load(QUrl(url)) self.app.exec_()
def get_canvas_instance(): for widget in QApplication.topLevelWidgets(): if isinstance(widget, CanvasMainWindow): return widget
print("Attributes: {0}".format(self.glProgram.attributes)) print("Uniforms: {0}".format(self.glProgram.uniforms)) w, h = 128, 128 data = (c_float * (w * h * 3))() for i in range(w * h): data[3*i] = i/float(w*h) data[3*i+1] = i/float(w*h) data[3*i+2] = i/float(w*h) glUniform4f(self.glProgram.uniforms['color'], 1., 0., 0., 1.) positions = (c_float * (4 * 2))( 0., 0., 1., 0., 0., 1., 1., 1.) glEnableVertexAttribArray(self.glProgram.attributes['position']) glVertexAttribPointer(self.glProgram.attributes['position'], 2, GL_FLOAT, GL_FALSE, 0, positions) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) def resizeGL(self, w, h): glViewport(0, 0, w, h) app = QApplication([]) widget = Test() widget.show() sys.exit(app.exec_())
def main(): app = QApplication(sys.argv) app_window = Gui() app_window.show() sys.exit(app.exec_())
super(ExceptionHandler, self).__init__() def handler(self, exctype, value, traceback): self.errorSignal.emit() #print "ERROR CAPTURED", value, traceback sys._excepthook(exctype, value, traceback) if __name__ == '__main__': import sys exceptionHandler = ExceptionHandler() sys._excepthook = sys.excepthook sys.excepthook = exceptionHandler.handler from PyQt4.QtGui import QApplication, QIcon import ctypes myappid = u'WISCXRAYASTRO.ADR3.MAGNETCONTROL.3' # arbitrary string ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) app = QApplication(sys.argv) app.setOrganizationName('McCammonLab') app.setOrganizationDomain('wisp.physics.wisc.edu') app.setApplicationName('ADR3 Magnet Control') app.setWindowIcon(QIcon('Icons/solenoid-round-150rg.png')) mw = MagnetControlWidget() mw.show() app.exec_()
def _persistModel(self, save_and_new): """ Saves the model to the database and shows a success message. :param save_and_new: A Boolean indicating it is triggered by save and new button. :type save_and_new: Boolean """ try: # Persist the model to its corresponding store. if self._mode == SAVE: self._model.save() if not save_and_new: QMessageBox.information( self, QApplication.translate( "MappedDialog","Record Saved" ), QApplication.translate( "MappedDialog", "New record has been successfully saved." ) ) else: self._model.update() QMessageBox.information( self, QApplication.translate("MappedDialog","Record Updated"), QApplication.translate( "MappedDialog", "Record has been successfully updated.") ) STDMDb.instance().session.flush() for attrMapper in self._attrMappers: control = attrMapper.valueHandler().control if isinstance(control, ExpressionLineEdit): value = control.on_expression_triggered() print attrMapper._attrName, value setattr(self.model(), attrMapper._attrName, value) self._model.update() # STDMDb.instance().session.flush() except Exception as ex: QMessageBox.critical( self, QApplication.translate( "MappedDialog", "Data Operation Error" ), QApplication.translate( "MappedDialog", u'The data could not be saved due to ' u'the error: \n{}'.format(ex.args[0]) ) ) self.is_valid = False # Close the dialog if isinstance(self, QDialog) and self.is_valid: self.postSaveUpdate(self._model) if not save_and_new: self.accept()
def set_instance(report): app_inst = QApplication.instance() app_inst._report_window = report
import unittest import sys import os import shutil from PyQt4.QtGui import QApplication from PyQt4.QtTest import QTest from PyQt4.QtCore import Qt import LogIT import Controller import GuiStore # Need to call this here to avoid some weird behaviour app = QApplication(sys.argv) class ModelExtractorTest(unittest.TestCase): def setUp(self): """ """ settings = LogIT.LogitSettings() settings.cur_settings_path = os.path.join(os.getcwd(), 'settings.logset') self.form = LogIT.MainGui(LogIT.LogitSettings()) self.extractor = self.form.widgets['Model Extractor'] def test_extractModel(self): """ """ in_path = r'C:\Users\duncan.runnacles\Documents\Programming\Python\Logit\Regression_Test_Data\Loader\model\Kennford\isis\iefs\kennford_1%AEP_FINAL_v5.18.ief' out_dir = r'C:\Some\fake\folder'
def main(): app = QApplication([]) q = MyWidget() q.show() app.exec_()
def setUpClass(cls): cls._app = QApplication([])
class PrincipalSearchTestCase(unittest.TestCase): """ Tests the principal search controller. """ _application = QApplication(sys.argv) def setUp(self): """ Creates the test setup. """ selectedItem = PrivilegeItemMock("/test/test.pdf") self._repositoryMock = PrivilegeRepositoryMock([selectedItem]) self._privilegeDialog = PrivilegeDialog(self._repositoryMock) self._privilegeDialog.item = selectedItem self._model = self._privilegeDialog._principalSearchModel self._controller = self._privilegeDialog._principalSearchController # Setup for testing the add principal interface self._items = list() self._application.connect( self._controller, SIGNAL(self._controller.ADD_PRINCIPAL_SIGNAL), self._addPrincipalCallback) def _addPrincipalCallback(self, items): """ Just add the retrieved items to C{self._items}. """ self._items = items def testSearchSuccess(self): """ Tests the successful default search. """ self._controller._searchButton.click() self._waitUntilFinished() self.assertEquals(self._model.rowCount(), 6) self.assertEquals(unicode(self._model.item(0, 0).text()), SPECIAL_PRINCIPALS[0].displayName) self.assertEquals(self._model.item(10, 0), None) self.assertEquals(self._repositoryMock.searchMode, 2) def testSearchSuccessUser(self): """ Tests the successful user-only search. """ self._controller._userFilterButton.setChecked(True) self._controller._searchButton.click() self._waitUntilFinished() self.assertEquals(self._model.rowCount(), 6) self.assertEquals(self._repositoryMock.searchMode, 0) def testSearchSuccessGroup(self): """ Tests the successful group-only search. """ self._controller._groupFilterButton.setChecked(True) self._controller._searchButton.click() self._waitUntilFinished() self.assertEquals(self._model.rowCount(), 6) self.assertEquals(self._repositoryMock.searchMode, 1) def _waitUntilFinished(self): """ Helper function which waits until the worker thread has finished. """ while not self._controller._workerThread.isFinished(): pass self._controller._searchCallback() def testSearchError(self): """ Tests the error handling of the search. """ self._repositoryMock.error = True self._controller._searchButton.click() self._waitUntilFinished() def testAddPrincipal(self): """ Tests the adding of principals. """ self._controller._addPrincipalButton.click() self.assertEquals(len(self._items), 0) index = self._model.index(0, 0) self._controller._resultWidget.selectionModel().select( index, QItemSelectionModel.SelectCurrent) self._controller._addPrincipalButton.click() self.assertEquals(len(self._items), 1) self.assertEquals( len(self._controller._resultWidget.selectedIndexes()), 0)
def send(cls, handlerObject, func, *args): e = ThunkEvent(func, *args) QApplication.sendEvent(handlerObject, e)
def create_orbital_track_shapefile_for_day (year, month, day, step_minutes, tle_line1, tle_line2, sat_name): """ Return memory QgsVectorLayer with points (WGS84) of satellite positions for given day with given period in minutes :param year: year of aquisition :param month: month of aquisition :param day: day of aquisition :param step_minutes: period of position modeling in minutes :param tle_line1: TLE Line 1 :param tle_line2: TLLE Line 2 :param sat_name: Name of satellite (e.g. Terra) :return: """ try: orb = Orbital("N",tle_file=None,line1=tle_line1, line2=tle_line2) except: raise NameError try: year = int(year) month = int(month) day = int(day) step_minutes = float(step_minutes) except: raise TypeError trackLayerName = 'Track Layer (' + str(sat_name) + ': ' + str(year) + ':' + str(month) + ':' + str(day) + ')' trackLayer = QgsVectorLayer("Point", trackLayerName, "memory") trackLayer.setCrs(QgsCoordinateReferenceSystem(4326)) trackLayerDataProvider = trackLayer.dataProvider() trackLayer.startEditing() trackLayerDataProvider.addAttributes( [ QgsField("ID", QVariant.Int), QgsField("TIME", QVariant.String), QgsField("LAT", QVariant.Double), QgsField("LON", QVariant.Double)] ) i = 0 minutes = 0 while minutes < 1440: QApplication.processEvents() utc_hour = int(minutes // 60) utc_minutes = int((minutes - (utc_hour*60)) // 1) utc_seconds = int(round((minutes - (utc_hour*60) - utc_minutes)*60)) utc_string = str(utc_hour) + ':' + str(utc_minutes) + ':' + str(utc_seconds) utc_time = datetime.datetime(year,month,day,utc_hour,utc_minutes,utc_seconds) lon, lat, alt = orb.get_lonlatalt(utc_time) trackPoint = QgsFeature() trackPoint.setGeometry(QgsGeometry.fromPoint(QgsPoint(lon,lat))) trackPoint.setAttributes([i,utc_string,float(lat),float(lon)]) trackLayerDataProvider.addFeatures ([trackPoint]) i += 1 minutes += step_minutes trackLayer.commitChanges() trackLayer.updateExtents() return trackLayer
def post(cls, handlerObject, func, *args): e = ThunkEvent(func, *args) QApplication.postEvent(handlerObject, e)
def __call__(self, i, imax): if dlg.wasCanceled(): raise Exception("aborted") dlg.setValue(int(i * 100 / imax)) QApplication.processEvents()