def testBasic(self): '''QFile.getChar''' obj = QFile(self.filename) obj.open(QIODevice.ReadOnly) self.assertEqual(obj.getChar(), (True, 'a')) self.assertFalse(obj.getChar()[0]) obj.close()
def __init__(self, parent=None): super(IPHelper, self).__init__(parent) f = QFile(os.path.join(os.path.split(__file__)[0], 'iphelper.ui')) loadUi(f, self) f.close() self.ipAddress = None # create validators validator = QRegExpValidator(QRegExp('\d{,3}')) self.uiFirstTetTXT.setValidator(validator) self.uiSecondTetTXT.setValidator(validator) self.uiThirdTetTXT.setValidator(validator) self.uiFourthTetTXT.setValidator(validator) # build a map of the buttons self.buttons = [None]*16 self.signalMapper = QSignalMapper(self) self.signalMapper.mapped.connect(self.tetMap) for button in self.findChildren(QPushButton): match = re.findall(r'^uiTrellis(\d{,2})BTN$', button.objectName()) if match: i = int(match[0]) self.buttons[i] = button if i >= 12: self.signalMapper.setMapping(button, i) button.clicked.connect(self.signalMapper.map) self.tetMap(12)
def loadDialog(file_name): loader = QUiLoader() the_file = QFile(file_name) the_file.open(QFile.ReadOnly) ret_val = loader.load(the_file) the_file.close() return ret_val
def convertTextureSize(texturePath): if int(cmds.about(v=1)) < 2017: from PySide import QtCore from PySide.QtGui import QPixmap, QImage from PySide.QtCore import QFile, QIODevice else: from PySide2 import QtCore from PySide2.QtGui import QPixmap, QImage from PySide2.QtCore import QFile, QIODevice folder, fileName = ntpath.split(texturePath) origFileName = fileName if fileName[: 8] != 'resized_' else fileName[ 8:] origPath = folder + '/' + origFileName if not os.path.exists(origPath): cmds.warning("original is not exists : %s" % texturePath) return convertedFileName = 'resized_%d_' % ( int(resolusion)) + origFileName renamedPath = folder + "/" + convertedFileName ext = os.path.splitext(fileName)[-1] img = QImage(origPath) pixmap = QPixmap() pixmap = pixmap.fromImage( img.scaled(int(resolusion), int(resolusion), QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.FastTransformation)) qfile = QFile(renamedPath) qfile.open(QIODevice.WriteOnly) pixmap.save(qfile, ext[1:], 100) qfile.close() return renamedPath
class TestQFileSignalBlocking(unittest.TestCase): '''Test case for blocking the signal QIODevice.aboutToClose()''' def setUp(self): #Set up the needed resources - A temp file and a QFile self.called = False handle, self.filename = mkstemp() os.close(handle) self.qfile = QFile(self.filename) def tearDown(self): #Release acquired resources os.remove(self.filename) del self.qfile def callback(self): #Default callback self.called = True def testAboutToCloseBlocking(self): #QIODevice.aboutToClose() blocking QObject.connect(self.qfile, SIGNAL('aboutToClose()'), self.callback) self.assert_(self.qfile.open(QFile.ReadOnly)) self.qfile.close() self.assert_(self.called) self.called = False self.qfile.blockSignals(True) self.assert_(self.qfile.open(QFile.ReadOnly)) self.qfile.close() self.assert_(not self.called)
def __init__(self): self.loader = QUiLoader() infile = QFile("resources/loading.ui") infile.open(QFile.ReadOnly) self.window = self.loader.load(infile, None) infile.close() self.overrides = {'personID':self.window.personID, 'paID':self.window.paID, 'maID':self.window.maID, 'sex':self.window.sex, 'affected':self.window.affected, 'n_local_aff':self.window.n_local_aff, 'n_local_desc':self.window.n_local_desc, 'nicki_d':self.window.nicki_d, 'is_root':self.window.is_root, 'is_leaf':self.window.is_leaf, 'generation':self.window.generation} self.requiredForCalculateD = set(['personID','paID','maID','sex','affected']) self.header = [] self.lowerHeader = [] self.window.browseInputButton.clicked.connect(self.browseInput) self.window.inputField.textChanged.connect(self.switchPrograms) self.window.browseOutputButton.clicked.connect(self.browseOutput) self.window.outputField.textChanged.connect(self.switchPrograms) self.window.programBox.currentIndexChanged.connect(self.switchPrograms) self.window.runButton.clicked.connect(self.go) self.switchPrograms() self.window.buttonBox.setEnabled(False) self.window.show()
def main(argv=None): if argv is None: argv = sys.argv app = QApplication(argv) engine = QScriptEngine() if HAS_DEBUGGER: debugger = QScriptEngineDebugger() debugger.attachTo(engine) debugWindow = debugger.standardWindow() debugWindow.resize(1024, 640) scriptFileName = './calculator.js' scriptFile = QFile(scriptFileName) scriptFile.open(QIODevice.ReadOnly) engine.evaluate(unicode(scriptFile.readAll()), scriptFileName) scriptFile.close() loader = QUiLoader() ui = loader.load(':/calculator.ui') ctor = engine.evaluate('Calculator') scriptUi = engine.newQObject(ui, QScriptEngine.ScriptOwnership) calc = ctor.construct([scriptUi]) if HAS_DEBUGGER: display = ui.findChild(QLineEdit, 'display') display.connect(display, SIGNAL('returnPressed()'), debugWindow, SLOT('show()')) ui.show() return app.exec_()
def findOrSaveConfig(self): infile = QFile('ui/config_path.ui') infile.open(QFile.ReadOnly) loader = QUiLoader() dialog = loader.load(infile, self.window) infile.close() def browse(): path = QFileDialog.getSaveFileName(dialog, u"Choose or create a configuration file", dialog.pathBox.text())[0] if path != '': dialog.pathBox.setText(path) def cancel(): dialog.hide() def ok(): autodetectPort = dialog.autodetect.checkState() == Qt.Checked configPath = os.path.expanduser(dialog.pathBox.text()) dialog.hide() self.start(configPath, autodetectPort) dialog.show() dialog.pathBox.setText(os.path.expanduser('~/.config/tangelo/tangelo.conf')) dialog.browseButton.clicked.connect(browse) dialog.cancelButton.clicked.connect(cancel) dialog.okButton.clicked.connect(ok)
def _write_doc_to_path(doc, path): # write QDomDocument to path as HROX hrox_file = QFile(path) if not hrox_file.open(QFile.WriteOnly): raise RuntimeError("Failed to open file for writing") stream = QTextStream(hrox_file) doc.save(stream, 1) hrox_file.close()
def save_to_disk(self, filename, data): f = QFile(filename) if not f.open(QIODevice.WriteOnly): print "could not open %s for writing" % filename return False f.write(data.readAll()) f.close() return True
def loadWindowFromFile(file_name): '''Load the window definition from the resource ui file''' loader = QUiLoader() ui_file = QFile(file_name) ui_file.open(QFile.ReadOnly) the_window = loader.load(ui_file) ui_file.close() return the_window
def _read_doc_from_path(path): # reading QDomDocument from HROX path hrox_file = QFile(path) if not hrox_file.open(QFile.ReadOnly): raise RuntimeError("Failed to open file for reading") doc = QDomDocument() doc.setContent(hrox_file) hrox_file.close() return doc
def loadHyperlinkDialog(self): ''' Load dialog from ui file for defining hyperlink ''' loader = QUiLoader() ui_file = QFile(':/hyperlink.ui') # UI_DIALOG_FILE) ui_file.open(QFile.ReadOnly) self.hyperlink_dialog = loader.load(ui_file) ui_file.close() self.hyperlink_dialog.accepted.connect(self.hyperlinkChanged) self.hlink_field = self.hyperlink_dialog.findChild(QLineEdit, 'hlink')
def readRcTextFile(path): """Read whole text file from qt resources system.""" assert path.startswith(':/') f = QFile(path) if not f.open(QFile.ReadOnly | QFile.Text): raise FileNotFoundError('failed to read rc text %s' % path) text = str(f.readAll()) f.close() return text
def testBug909(self): fileName = QFile(adjust_filename('bug_909.ui', __file__)) loader = QUiLoader() main_win = loader.load(fileName) self.assertEqual(sys.getrefcount(main_win), 2) fileName.close() tw = QTabWidget(main_win) main_win.setCentralWidget(tw) main_win.show()
def __load_ui(self): ui_path = os.path.dirname(__file__) ui_path = os.path.join(ui_path, "MainWindow.ui") ui_file = QFile(ui_path) ui_file.open(QFile.ReadOnly) ui_loader = QtUiTools.QUiLoader() self.__ui = ui_loader.load(ui_file, None) ui_file.close() self.__ui.answerTableWidget.setHorizontalHeaderLabels([self.tr("Question"), self.tr("Answer")])
def createWidget(self): # Override the existing widget # TODO: Do I need to delete anything explicitly? infile = QFile('ui/process_widget.ui') infile.open(QFile.ReadOnly) loader = QUiLoader() self.widget = loader.load(infile, Globals.mainWindow.window) infile.close() self.updateWidget(True)
def findTangelo(): infile = QFile('ui/find_tangelo.ui') infile.open(QFile.ReadOnly) loader = QUiLoader() dialog = loader.load(infile, None) infile.close() if sys.platform.startswith('win'): Globals.pythonPath = subprocess.Popen(['where', 'python'], stdout=subprocess.PIPE).communicate()[0].strip() Globals.tangeloPath = subprocess.Popen(['where', 'tangelo'], stdout=subprocess.PIPE).communicate()[0].strip() else: Globals.pythonPath = subprocess.Popen(['which', 'python'], stdout=subprocess.PIPE).communicate()[0].strip() Globals.tangeloPath = subprocess.Popen(['which', 'tangelo'], stdout=subprocess.PIPE).communicate()[0].strip() if os.path.exists(Globals.pythonPath): dialog.pythonPathBox.setText(Globals.pythonPath) if os.path.exists(Globals.tangeloPath): dialog.tangeloPathBox.setText(Globals.tangeloPath) def pythonBrowse(): path = QFileDialog.getOpenFileName(dialog, u"Find python", dialog.pythonPathBox.text())[0] if path != '': dialog.pythonPathBox.setText(path) def tangeloBrowse(): path = QFileDialog.getOpenFileName(dialog, u"Find tangelo", dialog.tangeloPathBox.text())[0] if path != '': dialog.tangeloPathBox.setText(path) def cancel(): dialog.hide() sys.exit() def ok(): Globals.pythonPath = os.path.expanduser(dialog.pythonPathBox.text()) Globals.tangeloPath = os.path.expanduser(dialog.tangeloPathBox.text()) if not os.path.exists(Globals.pythonPath): Globals.criticalError("Sorry, that python interpreter doesn't exist.") return if not os.path.exists(Globals.tangeloPath): Globals.criticalError("Sorry, that tangelo executable doesn't exist.") return Globals.mainWindow = Overview() Globals.mainWindow.refresh() dialog.hide() dialog.show() dialog.tangeloBrowse.clicked.connect(tangeloBrowse) dialog.pythonBrowse.clicked.connect(pythonBrowse) dialog.cancelButton.clicked.connect(cancel) dialog.okButton.clicked.connect(ok)
def testPhrase(self): #Test loading of quote.txt resource f = open(adjust_filename('quoteEnUS.txt', __file__), "r") orig = f.read() f.close() f = QFile(':/quote.txt') f.open(QIODevice.ReadOnly) #|QIODevice.Text) print("Error:", f.errorString()) copy = f.readAll() f.close() self.assertEqual(orig, copy)
def testImage(self): #Test loading of sample.png resource f = open(adjust_filename('sample.png', __file__), "rb") orig = f.read() f.close() f = QFile(':/sample.png') f.open(QIODevice.ReadOnly) copy = f.readAll() f.close() self.assertEqual(len(orig), len(copy)) self.assertEqual(orig, copy)
def widgetFromUIFile(filePath): """ Reads an ``.ui`` file and creates a new widget object from it. :param filePath: Where to find the ``.ui`` file :return: The new created widget """ loader = QUiLoader() UIFile = QFile(filePath) UIFile.open(QFile.ReadOnly) widget = loader.load(UIFile) UIFile.close() return widget
def loadWindow(self, uiFile, mainWindowAsParent=True, connectSlots=True): ''' Load a Window from UI file. ''' path = join(UI_PATH, uiFile) windowFile = QFile(path) windowFile.open(QIODevice.ReadOnly | QIODevice.Text) # Make all loaded windows children of mainWindow, except mainWindow itself window = self.uiLoader.load( windowFile, self.__mainWindow if mainWindowAsParent else None) windowFile.close() if connectSlots: QMetaObject.connectSlotsByName(window) return window
def getPanel(): global fcpdWBpath # read UI file ui_file = QFile(os.path.join(fcpdWBpath, "FCPDwb_taskpanel.ui")) ui_file.open(QFile.ReadOnly) widget = QUiLoader().load(ui_file) ui_file.close() # connection widget.btnLaunch.clicked.connect(lambda: launchPureData(widget)) widget.btnRunStop.clicked.connect(lambda: runStopServer(widget)) return widget
def createManager(self): if self.manager != None: self.updateManager() self.manager.show() else: # Create the window infile = QFile('ui/process_manager.ui') infile.open(QFile.ReadOnly) loader = QUiLoader() #TODO: This isn't working: loader.registerCustomWidget(ManagerHelper) self.manager = loader.load(infile, Globals.mainWindow.window) infile.close() self.updateManager(True) self.manager.show()
def __init__(self): # Load UI files infile = QFile("ui/overview.ui") infile.open(QFile.ReadOnly) loader = QUiLoader() #TODO: this isn't working: loader.registerCustomWidget(MainHelper) self.window = loader.load(infile, None) infile.close() self.processes = {} self.deadProcesses = {} # Events self.window.refreshButton.clicked.connect(self.refresh) self.window.startButton.clicked.connect(self.findOrSaveConfig) self.window.show()
def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Diablo Meter") size = QSize(530, 470) self.resize(size) # Load ui from gui definition file try: loader = QUiLoader() file = QFile("widgets/widgets.ui") file.open(QFile.ReadOnly) mainWindow = loader.load(file, self) file.close() except: self.warning_message("Error", "Can't find widgets definition file.\nIs the widgets folder in the same path as the executable?") sys.exit() #Reference to the components self.left_click_lcd = mainWindow.findChild(QLCDNumber, "left_click_lcd") self.right_click_lcd = mainWindow.findChild(QLCDNumber, "right_click_lcd") self.action_keys_lcds = [mainWindow.findChild(QLCDNumber, "action_1_lcd"), mainWindow.findChild(QLCDNumber, "action_2_lcd"), mainWindow.findChild(QLCDNumber, "action_3_lcd"), mainWindow.findChild(QLCDNumber, "action_4_lcd")] options_menu = self.menuBar().addMenu("&Options") options_menu.addAction(QtGui.QAction("&Restart Counters", self, triggered=self.restart_counters)) #Queue to share messsages to the message pupm on EventListener q = Queue() self.event_listener = EventListener(q) self.event_listener.start() self.thread = EventProcessor(q) self.thread.dataReady.connect(self.on_hook_event) self.thread.start() #Key Names we are interested in. The order in the tuple #determines to which action key it's mapped self.key_maps = ("1", "2", "3", "4")
def javaInclude(context, engine): fileName = context.argument(0).toString() scriptFile = QFile("commands/" + fileName) if not scriptFile.open(QIODevice.ReadOnly): return -1 stream = QTextStream(scriptFile) s = stream.readAll() # QString scriptFile.close() parent = context.parentContext() # QScriptContext* if parent != 0: context.setActivationObject(context.parentContext().activationObject()) context.setThisObject(context.parentContext().thisObject()) result = engine.evaluate(s) #TODO/PORT/FIXME# what's this for? return 0
def __init__(self, ped): self.state = AppState(ped) self.loader = QUiLoader() infile = QFile("resources/vis.ui") infile.open(QFile.ReadOnly) self.window = self.loader.load(infile, None) infile.close() # Add our custom table self.tableWidget = TableComponent(self.state) self.window.historyDataSplitter.insertWidget(0,self.tableWidget) self.window.historyDataSplitter.update() # Add our pedigree view with its settings widgets settingsWidgets = {'canvasWidth':self.window.canvasWidth, 'canvasHeight':self.window.canvasHeight} self.pedigreeView = PedigreeComponent(settingsWidgets, self.state) self.window.pedigreeSplitter.insertWidget(0,self.pedigreeView) self.window.pedigreeSplitter.update() self.window.showMaximized()
def webLoadFinished(self, loaded): print("We loaded a web page") infile = QFile(self) infile.setFileName("ui/resources/jquery-1.9.1.js") if not infile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text): print("Error opening file: " + infile.errorString()) stream = QtCore.QTextStream(infile) self.jQuery = stream.readAll() infile.close() print("We loaded jQuery") self._web_view.page().mainFrame().evaluateJavaScript(self.jQuery) print("We evaluated jQuery") self._web_view.page().mainFrame().evaluateJavaScript("$( 'div.header' ).css( '-webkit-transition', '-webkit-transform 2s'); $( 'div.header' ).css('-webkit-transform', 'rotate(360deg)')") print("Ran some simple jQuery")
def exportContact(self, jid, name): cm = self.manager phoneContacts = cm.getQtContacts() contacts = [] for c in phoneContacts: if name == c.displayLabel(): if os.path.isfile(WAConstants.CACHE_CONTACTS + "/" + name + ".vcf"): os.remove(WAConstants.CACHE_CONTACTS + "/" + name + ".vcf") print "founded contact: " + c.displayLabel() contacts.append(c) openfile = QFile(WAConstants.VCARD_PATH + "/" + name + ".vcf") openfile.open(QIODevice.WriteOnly) if openfile.isWritable(): exporter = QVersitContactExporter() if exporter.exportContacts(contacts, QVersitDocument.VCard30Type): documents = exporter.documents() writer = QVersitWriter() writer.setDevice(openfile) writer.startWriting(documents) writer.waitForFinished() openfile.close() self.contactExported.emit(jid, name) break
def __init__(self): self.loadedPaths = set() self.dataSources = [] self.genes = set() self.loader = QUiLoader() infile = QFile("expressionTopology.ui") infile.open(QFile.ReadOnly) self.window = self.loader.load(infile, None) infile.close() self.updateTimeSliders() # Main view self.multiPanel = multiViewPanel(self.window.graphicsView,self) # Events self.window.categoryTable.cellClicked.connect(self.changeColor) self.window.loadButton.clicked.connect(self.loadData) self.window.quitButton.clicked.connect(self.window.close) self.window.addButton.clicked.connect(self.addGene) self.window.geneBox.editTextChanged.connect(self.editGene) self.window.speedSlider.valueChanged.connect(self.changeSpeed) self.window.timeSlider.valueChanged.connect(self.changeTime) self.window.addButton.setEnabled(False) self.window.showFullScreen() #self.window.show() # Start timer # Update timer self.timer = QTimer(self.window) self.timer.timeout.connect(self.nextFrame) self.timer.start(Viz.FRAME_DURATION)
def __init__(self, *args, **kwargs): super(MainWindowController, self).__init__(*args, **kwargs) # vars self._address_valid = False # define ui members for type hinting self._ip_line_edit = self._window.IpAddressLineEdit # type: QLineEdit self._status_label = self._window.Statuslabel # type: QLabel self._update_button = self._window.UpdateButton # type: QPushButton self._update_button = self._window.UpdateButton # type: QPushButton self._progress_bar = self._window.progressBar # type: QProgressBar self._combobox = self._window.comboBox # type: QComboBox # load ui loader = QUiLoader() ui = QFile("ui/main_window.ui") ui.open(QFile.ReadOnly) self._window = loader.load(ui) # type: QWidget ui.close() self._window.show() # init other elements self._init_ip_line_edit()
class Update_Window(QDialog): # def __init__(self, parent=None): # QDialog.__init__(self, parent) def __init__(self, parent=None): super(Update_Window, self).__init__(parent) self.getPath_update = os.path.abspath(os.path.join('gui', 'pp_update.ui')) try: self.ui_pp_update = QUiLoader() self.file = QFile(self.getPath_search_ui, self) self.file.open(QFile.ReadOnly) self.myWidget = self.ui_pp_update.load(file, self) self.file.close() print "STATUS [OK] ", FILE_NAME, ": GUI is loaded from PySide" except: self.ui_pp_update = loadUi(self.getPath_update, self) print "STATUS [OK] ", FILE_NAME, ": GUI is loaded from PyQt4" self.ui_pp_update.setWindowModality(Qt.ApplicationModal) # Set data for download and saving in path self.location = os.path.abspath(os.path.join('temp', 'example-app-0.3.win32.zip')) self.url = 'http://sophus.bplaced.net/download/example-app-0.3.win32.zip' self.download_task = Download_Thread(self.location, self.url) self.download_task.notify_progress.connect(self.on_progress) self.download_task.finished_thread.connect(self.on_finished) self.download_task.error_http.connect(self.on_HTTPError) self.download_task.finished_download.connect(self.on_finish_download) self.ui_pp_update.pushButtonUpdate.setEnabled(True) self.create_actions_buttons() def on_start(self): self.ui_pp_update.progressBarUpdate.setRange(0, 0) self.download_task.start() def on_finish_download(self): msg_box = QMessageBox() QMessageBox.question(msg_box, ' Message ', "The file has been fully downloaded.", msg_box.Ok) def on_HTTPError(self): reply = QMessageBox.question(self, ' Error ', "The file could not be downloaded. Will they do it again?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.on_start() else: event.ignore() def on_progress(self, i): self.ui_pp_update.progressBarUpdate.setRange(0, 100) self.ui_pp_update.progressBarUpdate.setValue(i) def stop_progress(self): self.download_task.stop() self.ui_pp_update.progressBarUpdate.setValue(0) def check_folder_exists(self): location = os.path.abspath(os.path.join('temp')) if not os.path.exists(location): os.makedirs(location) print "Folder was created" self.on_start() else: print "Folder already exists" self.on_start() def on_finished(self): self.download_task.stop() self.ui_pp_update.progressBarUpdate.setValue(0) self.close() def set_ui_pp_update(self): self.ui_pp_update.progressBarUpdate.setAlignment(Qt.AlignCenter) self.ui_pp_update.progressBarUpdate.setValue(0) def create_actions_buttons(self): self.ui_pp_update.pushButtonUpdate.clicked.connect(self.check_folder_exists) self.ui_pp_update.pushButtonCancel.clicked.connect(self.stop_progress) self.ui_pp_update.pushButtonClose.clicked.connect(self.on_finished) def closeEvent(self, event): self.download_task.stop() def show_and_raise(self): self.show() self.raise_()
def load_ui_widget(filename, parent): loader = QUiLoader() uifile = QFile(filename) uifile.open(QFile.ReadOnly) loader.load(uifile, parent) uifile.close()
self.__conf["mainWindowGeometry"] = self.saveGeometry() self.__conf["mainWindowState"] = self.saveState() if __name__ == "__main__": ret = 0 log = QFile("log") log.open(QIODevice.WriteOnly) try: app = QApplication(sys.argv) locale = QLocale.system().name() translator = QTranslator() translator.load("qt_" + locale, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(translator) # Configuration de la base de données db = QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName('private/gem.db') db.open() # Création de l'_ui principale et boucle principale ui = GestionAbsences() ui.show() ret = app.exec_() except Exception: traceback.print_exc(file=log) log.close() sys.exit(ret)