def updateFileMenu(self): """ Updates the file menu dynamically, so that recent files can be shown. """ self.menuFile.clear() # self.menuFile.addAction(self.actionNew) # disable for now self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addAction(self.actionClose_Model) recentFiles = [] for filename in self.recentFiles: if QFile.exists(filename): recentFiles.append(filename) if len(self.recentFiles) > 0: self.menuFile.addSeparator() for i, filename in enumerate(recentFiles): action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self) action.setData(filename) action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName()) action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1 + i))) action.triggered.connect(self.load_model) self.menuFile.addAction(action) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit)
def read(self, fileName): self.state = PluginState.Invalid self.hasError = False self.dependencies = [] specFile = QFile(fileName) if not specFile.exists(): msg = QCoreApplication.translate(None, "File does not exist: {name}") return self.__reportError(msg.format(name=specFile.fileName())) if not specFile.open(QIODevice.ReadOnly): msg = QCoreApplication.translate(None, "Could not open file for read: {name}") return self.__reportError(msg.format(name=specFile.fileName())) fileInfo = QFileInfo(specFile) self.location = fileInfo.absolutePath() self.filePath = fileInfo.absoluteFilePath() reader = QXmlStreamReader(specFile) while not reader.atEnd(): reader.readNext() tokenType = reader.tokenType() if tokenType is QXmlStreamReader.StartElement: self.__readPluginSpec(reader) else: pass if reader.hasError(): msg = QCoreApplication.translate(None, "Error parsing file {0}: {1}, at line {2}, column {3}") return self.__reportError(msg.format(specFile.fileName(), reader.errorString(), reader.lineNumber(), reader.columnNumber())) self.state = PluginState.Read return True
def updateFileMenu(self): """ Updates the file menu dynamically, so that recent files can be shown. """ self.menuFile.clear() # self.menuFile.addAction(self.actionNew) # disable for now self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionSave_as) self.menuFile.addAction(self.actionClose_Model) recentFiles = [] for filename in self.recentFiles: if QFile.exists(filename): recentFiles.append(filename) if len(self.recentFiles) > 0: self.menuFile.addSeparator() for i, filename in enumerate(recentFiles): action = QAction("&%d %s" % (i + 1, QFileInfo(filename).fileName()), self) action.setData(filename) action.setStatusTip("Opens recent file %s" % QFileInfo(filename).fileName()) action.setShortcut(QKeySequence(Qt.CTRL | (Qt.Key_1+i))) action.triggered.connect(self.load_model) #self.connect(action, SIGNAL("triggered()"), self.load_model) self.menuFile.addAction(action) self.menuFile.addSeparator() self.menuFile.addAction(self.actionQuit)
def get_file_name(self, url): path = url.path() basename = QFileInfo(path).fileName() if not basename: basename = "download" if QFile.exists(basename): print "aaaaaaaaaaaaaaaah" return return basename
def download_file(self, path, setting): version_file = self.settings['base_url'].format( self.selected_version()) location = self.get_setting('download_dir').value versions = re.findall('v(\d+)\.(\d+)\.(\d+)', path)[0] minor = int(versions[1]) if minor >= 12: path = path.replace('node-webkit', 'nwjs') self.progress_text = 'Downloading {}'.format( path.replace(version_file, '')) url = QUrl(path) file_name = setting.save_file_path(self.selected_version(), location) archive_exists = QFile.exists(file_name) #dest_files_exist = False # for dest_file in setting.dest_files: # dest_file_path = os.path.join('files', setting.name, dest_file) # dest_files_exist &= QFile.exists(dest_file_path) forced = self.get_setting('force_download').value if archive_exists and not forced: self.continue_downloading_or_extract() return self.out_file = QFile(file_name) if not self.out_file.open(QIODevice.WriteOnly): error = self.out_file.error().name self.show_error('Unable to save the file {}: {}.'.format( file_name, error)) self.out_file = None self.enable_ui() return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.http_request_aborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.http_get_id = self.http.get(path, self.out_file)
def downloadFile(self, path, setting): self.progress_text = 'Downloading {}'.format(path.replace(self.base_url.format(self.selected_version()),'')) url = QUrl(path) fileInfo = QFileInfo(url.path()) fileName = setting.save_file_path(self.selected_version()) archive_exists = QFile.exists(fileName) dest_files_exist = True for dest_file in setting.dest_files: dest_file_path = os.path.join('files', setting.name, dest_file) dest_files_exist &= QFile.exists(dest_file_path) forced = self.getSetting('force_download').value if (archive_exists or dest_files_exist) and not forced: self.continueDownloadingOrExtract() return #QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): self.show_error('Unable to save the file {}: {}.'.format(fileName, self.outFile.errorString())) self.outFile = None self.enableUI() return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def download_file(self, path, setting): version_file = self.settings['base_url'].format(self.selected_version()) location = self.get_setting('download_dir').value versions = re.findall('v(\d+)\.(\d+)\.(\d+)', path)[0] minor = int(versions[1]) if minor >= 12: path = path.replace('node-webkit', 'nwjs') self.progress_text = 'Downloading {}'.format(path.replace(version_file, '')) url = QUrl(path) file_name = setting.save_file_path(self.selected_version(), location) archive_exists = QFile.exists(file_name) #dest_files_exist = False # for dest_file in setting.dest_files: # dest_file_path = os.path.join('files', setting.name, dest_file) # dest_files_exist &= QFile.exists(dest_file_path) forced = self.get_setting('force_download').value if archive_exists and not forced: self.continue_downloading_or_extract() return self.out_file = QFile(file_name) if not self.out_file.open(QIODevice.WriteOnly): error = self.out_file.error().name self.show_error('Unable to save the file {}: {}.'.format(file_name, error)) self.out_file = None self.enable_ui() return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.http_request_aborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.http_get_id = self.http.get(path, self.out_file)
def load_initial_data(self): settings = QSettings() dbfile = unicode(settings.value("Database/LastDb")) modelname = unicode(settings.value("Database/DefaultModel")) if dbfile and QFile.exists(dbfile): self.load_db(dbfile, modelname=modelname) self.logger.debug("Loaded database %s with model %s" % (dbfile, modelname)) if settings.value("Database/visibleFields"): visible_fields = [item for item in settings.value("Database/visibleFields")] # FIXME: in absence of QVariant, deal with values visible_fields = [False if item == 'false' else True for item in visible_fields] if not all(visible_fields): self.logger.debug("Hiding fields %s" % visible_fields) self.show_fields(visible_fields)
def dbConnect(): db = QSqlDatabase.addDatabase("QSQLITE") filename = "pythonthusiast.db" database = QFile(filename) if not database.exists(): qDebug("Database not found. Creating and opening") db.setDatabaseName(filename) db.open() query = QSqlQuery() query.exec_("create table qtapp_users " "(id integer primary key autoincrement, " "username varchar(30), " "password varchar(255))") query.prepare("insert into qtapp_users(username, password) values(:username, :password)") query.bindValue(":username", "eko") query.bindValue(":password", computeHash("password")) query.exec_() else: qDebug("Database found. Opening") db.setDatabaseName(filename) db.open() return db.isOpen()
def load_stylesheet(pyside=True): f = QFile(":petfactoryStyle/style.qss") if not f.exists(): pass else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #353434; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def load_stylesheet(theme, pyside=True): """ Loads the stylesheet. Takes care of importing the rc module. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ if theme == 'darkstyle': import themes.darkstyle.pyside_style_rc elif theme == 'robotstyle': import themes.robotstyle.pyside_style_rc from PySide.QtCore import QFile, QTextStream basedir = os.path.abspath(os.path.dirname(__file__)) localPath = "%s/style.qss" % theme f = QFile( os.path.join(basedir, localPath)) if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() # if platform.system().lower() == 'darwin': # see issue #12 on github # mac_fix = ''' # QDockWidget::title # { # background-color: #353434; # text-align: center; # height: 10px; # } # ''' # stylesheet += mac_fix return stylesheet
def main(argv): """ TOWRITE :param `argc`: TOWRITE :type `argc`: int :param `argv`: TOWRITE :type `argv`: char :rtype: int """ filesToOpen = [] # QStringList filesToOpen; filesToCheck = [] bindings = defaultBindings bindings_flag = False for arg in argv[1:]: if bindings_flag: bindings_flag = False if not arg in ("pyside", "pyqt4"): usage() else: bindings = arg elif arg == "-d" or arg == "--debug": pass elif arg == "-h" or arg == "--help": usage() elif arg == "-v" or arg == "--version": version() elif arg == "-b" or arg == "--bindings": bindings_flag = True else: filesToCheck.append(arg) if exitApp: return 1 # make global to all modules if bindings == "pyside": builtins.PYSIDE = True builtins.PYQT4 = False elif bindings == "pyqt4": builtins.PYSIDE = False builtins.PYQT4 = True if PYSIDE: from PySide.QtScript import QScriptEngine if not hasattr(QScriptEngine, "newFunction"): raise ImportError( 'You need a patched version of PySide.\n' 'see: https://codereview.qt-project.org/112333') #--PySide Imports. if PYSIDE: from PySide.QtCore import QObject, SIGNAL, SLOT, QFile from PySide.QtGui import QApplication elif PYQT4: import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) from PyQt4.QtCore import QObject, SIGNAL, SLOT, QFile from PyQt4.QtGui import QApplication from mainwindow import MainWindow for file_ in filesToCheck: if QFile.exists(file_) and MainWindow.validFileFormat(file_): filesToOpen.append(file_) else: usage() break if exitApp: return 1 app = QApplication(argv) app.setApplicationName(_appName_) app.setApplicationVersion(_appVer_) mainWin = MainWindow() # MainWindow* QObject.connect(app, SIGNAL("lastWindowClosed()"), mainWin, SLOT("quit()")) mainWin.setWindowTitle(app.applicationName() + " " + app.applicationVersion()) mainWin.show() # NOTE: If openFilesSelected() is called from within the mainWin constructor, slot commands wont work and the window menu will be screwed if filesToOpen: # if(!filesToOpen.isEmpty()) mainWin.openFilesSelected(filesToOpen) # return app.exec_() return app.exec_()
def testCallingStaticMethodWithClass(self): '''Call static method using class.''' self.assert_(QFile.exists(self.existing_filename)) self.assertFalse(QFile.exists(self.non_existing_filename))
def testCallingStaticMethodWithInstance(self): '''Call static method using instance of class.''' f = QFile(self.non_existing_filename) self.assert_(f.exists(self.existing_filename)) self.assertFalse(f.exists(self.non_existing_filename))
def main(argv): """ TOWRITE :param `argc`: TOWRITE :type `argc`: int :param `argv`: TOWRITE :type `argv`: char :rtype: int """ filesToOpen = [] # QStringList filesToOpen; filesToCheck = [] bindings = defaultBindings bindings_flag = False for arg in argv[1:]: if bindings_flag: bindings_flag = False if not arg in ("pyside", "pyqt4"): usage() else: bindings = arg elif arg == "-d" or arg == "--debug": pass elif arg == "-h" or arg == "--help": usage() elif arg == "-v" or arg == "--version": version() elif arg == "-b" or arg == "--bindings": bindings_flag = True else: filesToCheck.append(arg) if exitApp: return 1 # make global to all modules if bindings == "pyside": builtins.PYSIDE = True builtins.PYQT4 = False elif bindings == "pyqt4": builtins.PYSIDE = False builtins.PYQT4 = True if PYSIDE: from PySide.QtScript import QScriptEngine if not hasattr(QScriptEngine, "newFunction"): raise ImportError("You need a patched version of PySide.\n" "see: https://codereview.qt-project.org/112333") # --PySide Imports. if PYSIDE: from PySide.QtCore import QObject, SIGNAL, SLOT, QFile from PySide.QtGui import QApplication elif PYQT4: import sip sip.setapi("QString", 2) sip.setapi("QVariant", 2) from PyQt4.QtCore import QObject, SIGNAL, SLOT, QFile from PyQt4.QtGui import QApplication from mainwindow import MainWindow for file_ in filesToCheck: if QFile.exists(file_) and MainWindow.validFileFormat(file_): filesToOpen.append(file_) else: usage() break if exitApp: return 1 app = QApplication(argv) app.setApplicationName(_appName_) app.setApplicationVersion(_appVer_) mainWin = MainWindow() # MainWindow* QObject.connect(app, SIGNAL("lastWindowClosed()"), mainWin, SLOT("quit()")) mainWin.setWindowTitle(app.applicationName() + " " + app.applicationVersion()) mainWin.show() # NOTE: If openFilesSelected() is called from within the mainWin constructor, slot commands wont work and the window menu will be screwed if filesToOpen: # if(!filesToOpen.isEmpty()) mainWin.openFilesSelected(filesToOpen) # return app.exec_() return app.exec_()
def testCallingInstanceMethod(self): '''Call instance method.''' f1 = QFile(self.non_existing_filename) self.assertFalse(f1.exists()) f2 = QFile(self.existing_filename) self.assert_(f2.exists())