Beispiel #1
0
 def saveArtifactOrder(self,event,fileName=None):
     diag = QFileDialog(self,"Open Bookmark File", QtCore.QDir.currentPath())
     if fileName is None:
         filename,filetype = QFileDialog.getSaveFileName(self,"Open Bookmark File",os.path.join(QtCore.QDir.currentPath(),self.XML_Read.getValue(['Paths','ArtifactOrderSettingsDefault'])),
             "XML Files (*.xml)")
     else:
         filename = fileName
     fh = QFile(filename)
     if not fh.open(QIODevice.WriteOnly):
         print('IOERROR')
     self.currentXMLfilepath = filename
     stream = QXmlStreamWriter(fh)
     
     stream.setAutoFormatting(True)
     stream.writeStartDocument()
     stream.writeStartElement("Data")
     stream.writeStartElement("Order")
     for i in range(self.verticalLayout.count()):
         print(self.verticalLayout.itemAt(i).widget().text())
         stream.writeTextElement(self.verticalLayout.itemAt(i).widget().xml_text, "")
     #stream.writeAttribute("href", "http://qt-project.org/")
     stream.writeEndElement()
     stream.writeStartElement('PauseInBetweenTrials')
     stream.writeTextElement('Minute',str(self.timeEditInBetweenTrials.time().minute()))
     stream.writeTextElement('Second',str(self.timeEditInBetweenTrials.time().second()))
     stream.writeEndElement()
     stream.writeTextElement('AmountOfTrials',str(self.sbAmountTrials.value()))
     stream.writeEndElement()
     stream.writeEndDocument()
Beispiel #2
0
    def loadGeom (self):
        geometry = {'polygon':[]}
        filename = self.name+"_geometry.txt"
        filename = filename.lower()
        filename = os.path.join(Config().instance.path_to_icons(),"empire","32x32",filename)
        file = QFile(filename)
        if file.open(QIODevice.ReadOnly):

            stream = QTextStream(file)
            
            while (not stream.atEnd()):
                line = stream.readLine()
                if line[0]!= "#":
                    elts = line.split(' ')
                    l = []
                    print ('line',line)
                    for i in range (1,len(elts)):
                        try :
                            l.append(QPoint(int(elts[i].split(',')[0]),int(elts[i].split(',')[1])))
                        except IndexError :
                            qDebug("Warning : empire.loadgeom, probleme lecture paire de point")
                    if (elts[0] == "p"):
                        print ('add polygon')
                        geometry['polygon'].append( l )
                    else:
                        pass
        else : 
            print ('not able to load file',filename)
        return geometry
Beispiel #3
0
 def saveSettings(self,event,filename=None):
     if not filename:
         filename,filetype = QFileDialog.getSaveFileName(self,"Open Bookmark File", os.path.join(QtCore.QDir.currentPath(),self.XML_Read.getValue(['Paths','TrialSettingsDefault'])),
             "XML Files (*.xml)")
     fh = QFile(filename)
     if not fh.open(QIODevice.WriteOnly):
         print('IOERROR')
     self.currentXMLfilepath = filename
     stream = QXmlStreamWriter(fh)
     
     stream.setAutoFormatting(True)
     stream.writeStartDocument()
     stream.writeStartElement("Data")
     stream.writeStartElement("TrialSettings")
     stream.writeStartElement('GeneralSettings')
     
     stream.writeTextElement(self.sbTrialDuration.objectName(),str(self.sbTrialDuration.value()))
     stream.writeTextElement(self.sbStimulusDuration.objectName(),str(self.sbStimulusDuration.value()))
     stream.writeTextElement(self.sbPause.objectName(),str(self.sbPause.value()))
     stream.writeTextElement(self.cbRandomizeStimuli.objectName(),str(self.cbRandomizeStimuli.checkState()))
     stream.writeEndElement()
     stream.writeStartElement('Artifacts')
     stream.writeAttribute('Checked',str(self.rbArtifacts.isChecked()))
     stream.writeEndElement()
     stream.writeStartElement('ERP')
     stream.writeAttribute('Checked',str(self.rbERP.isChecked()))
     stream.writeTextElement(self.cbProbability.objectName(),str(self.cbProbability.currentText()))
     stream.writeEndElement()
     stream.writeEndElement()
     stream.writeEndElement()
     stream.writeEndDocument()
    def _deleteSession(self, filePath):
        result = QMessageBox.information(gVar.app.activeWindow(), _('Delete Session'),
            _('Are you sure you want to delete session \'%s\'?') % QFileInfo(filePath).completeBaseName(),
            QMessageBox.Yes | QMessageBox.No)

        if result == QMessageBox.Yes:
            QFile.remove(filePath)
Beispiel #5
0
    def append_metadata_req_parts(self):
        metadata = self.db.get_proxy_metadata(self.book_id)
        language = next(iter(metadata.languages), None)
        summary = metadata.comments
        isbn = metadata.isbn
        issued_on = metadata.pubdate.date().isoformat()
        if issued_on == '0101-01-01':
            issued_on = None

        self.req_body.append(
            self.build_req_part('metadata[calibre_metadata_digest]',
                                self.metadata_digest))
        self.req_body.append(
            self.build_req_part('metadata[title]', metadata.title))
        if summary:
            self.req_body.append(
                self.build_req_part('metadata[summary]', summary))
        if language:
            self.req_body.append(
                self.build_req_part('metadata[language]', language))
        if isbn:
            self.req_body.append(self.build_req_part('metadata[isbn]', isbn))
        if issued_on:
            self.req_body.append(
                self.build_req_part('metadata[issued_on]', issued_on))

        for series_item in self.get_series(metadata):
            self.req_body.append(
                self.build_req_part('metadata[series][][title]',
                                    series_item['title']))
            if series_item['index'] is not None:
                self.req_body.append(
                    self.build_req_part('metadata[series][][index]',
                                        str(series_item['index'])))

        for author in metadata.authors:
            self.req_body.append(
                self.build_req_part('metadata[author_list][]', author))
        for tag in metadata.tags:
            self.req_body.append(
                self.build_req_part('metadata[tag_list][]', tag))

        bookshelves = self.get_bookshelves(metadata)
        if bookshelves is not None:
            self.req_body.append(
                self.build_req_part('metadata[bookshelves][]', ''))
            for bookshelf in bookshelves:
                self.req_body.append(
                    self.build_req_part('metadata[bookshelves][]', bookshelf))

        cover_path = self.db.cover(self.book_id, as_path=True)
        if cover_path:
            self.cover = QFile(cover_path)
            self.cover.open(QIODevice.ReadOnly)
            self.req_body.append(
                self.build_req_part('metadata[cover]', self.cover))
        else:
            self.cover = None
Beispiel #6
0
    def __init__(self, parent=None):
        super(HttpsDownloader, self).__init__(parent)

        self._manager = QNetworkAccessManager(self)
        self._attributes = DownloaderAttributes(
            DownloaderAttributes.UrlType.Https, self)
        self._tmpFile = QFile(self)
        self._configFile = QFile(self)
        self._reply = None
    def backupSavedSessions(self):
        if not QFile.exists(self._lastActiveSessionPath):
            return

        if QFile.exists(self._firstBackupSession):
            QFile.remove(self._secondBackupSession)
            QFile.copy(self._firstBackupSession, self._secondBackupSession)

        QFile.remove(self._firstBackupSession)
        QFile.copy(self._lastActiveSessionPath, self._firstBackupSession)
Beispiel #8
0
    def save (self,filename = None):
        print ("sauvegarde")
        progress = QProgressDialog ()
        progress.setWindowModality(QtCore.Qt.WindowModal)
        progress.setLabelText("Sauvegarde")
        progress.setMaximum(len(self.getWarriorList())+1)
        #db_name = self.database.database.databaseName()
        if filename == None : 
            filename = os.path.join(Config().instance.path_to_sqlite(),self.settings.value("global/current_database"))
        try :
            print ('current filename', filename)
            # backup 
            filename_bkp = filename+"_"+QtCore.QDateTime.currentDateTime().toString("yyyy-MM-dd-hh-mm-ss")
            QFile.copy(filename,filename_bkp)
            if QFile.remove(filename) == False :
                qWarning("echec suppression ")
            else:
                qWarning("reussite suppression %s"% filename)                
        except OSError :
            qWarning("echec suppression ")

        result = QFile.copy(Config().instance.model_database(),filename)
        if result == False :
            print("echec de la copy ",Config().instance.model_database(),filename)
            return
        else:
            print("copy du model reussit")
            database = DatabaseManager(filename,True)
            database.createConnection()
            database.setVerbose(True)
        for faction in self.factions.values() :
            attribs = faction.getDictAttributes ()
            database.insert("gm_faction",attribs)
            for empire in faction.empires.values():
                attribs = empire.getDictAttributes ()
                database.insert("gm_empire",attribs)
                for kingdom in empire.kingdoms.values():
                    attribs = kingdom.getDictAttributes ()
                    database.insert("gm_kingdom",attribs)
                    for temple in kingdom.temples:
                        attribs = temple.getDictAttributes ()
                        database.insert("gm_temple",attribs)                        
                    for groupe in kingdom.groupes.values():
                        attribs = groupe.getDictAttributes ()
                        database.insert("gm_groupe",attribs)
                        for sub_groupe in groupe.sub_groupes:
                            attribs = sub_groupe.getDictAttributes ()
                            database.insert("gm_groupe",attribs)
                            for perso in sub_groupe.warriors.values():
                                attribs = perso.getDictAttributes ()
                                database.insert("gm_perso",attribs)
                        for perso in groupe.warriors.values():
                            attribs = perso.getDictAttributes ()
                            database.insert("gm_perso",attribs)
                            progress.setValue(progress.value()+1)
Beispiel #9
0
 def deleteFile(self, path, name):
     file = QFile(path + name + ".tmp")
     print(file.fileName())
     if file.exists():
         print(file.remove())
     file.setFileName(path + name + ".tmp.cfg")
     if file.exists():
         print(file.remove())
Beispiel #10
0
 def setThemeFromGtk():
     f = QFile(QDir.homePath() + "/.gtkrc-2.0")
     if not f.open(QIODevice.ReadOnly | QIODevice.Text):
         return
     while not f.atEnd():
         l = f.readLine().trimmed()
         if l.startsWith("gtk-icon-theme-name="):
             s = l.split('=')[-1]
             syslog.syslog(syslog.LOG_DEBUG,
                           "DEBUG  setting gtk theme %s" % str(s))
             QIcon.setThemeName(s.remove('"'))
             break
Beispiel #11
0
    def upload(self):
        self.file = QFile(self.file_path)
        self.file.open(QIODevice.ReadOnly)

        self.req = QNetworkRequest(QUrl(self.upload_url))

        self.req_body = QHttpMultiPart(QHttpMultiPart.FormDataType)
        for key, value in self.upload_params.items():
            self.log_info('{}={}'.format(key, value))
            self.req_body.append(self.build_req_part(key, value))
        self.req_body.append(self.build_req_part('file', self.file))

        self.reply = self.network.post(self.req, self.req_body)
        self.reply.finished.connect(self.complete_upload)
        self.reply.uploadProgress.connect(self.upload_progress)
Beispiel #12
0
 def set_page(self):
     if self.force_compile or not exists(realpath('./data/compiled/index.html')) or \
             getmtime(realpath('./interface/index.html')) > getmtime(realpath('./data/compiled/index.html')):
         self._compile_template('index.html', './data/compiled/index.html')
     qFile_page = QFile(realpath('./data/compiled/index.html'))
     self.web_view.load(
         QUrl.fromLocalFile(QFileInfo(qFile_page).absoluteFilePath()))
     self.web_page.selectionChanged.emit()
 def __init__(self, parent=None):
     super().__init__(parent)
     self._key = ''
     self._value = ''
     self._path = ''
     self._file = QFile()
     self._stream = QTextStream()
     self._lines = []
Beispiel #14
0
def read_qt_resource(path, encoding=None):
    """Reads a resource from the file system or a packaged Qt resource file.
  Returns either binary or text data, depending on whether encoding is None.
  path -- Path to the resource. Should start with ":" if referencing a resource inside a packaged Qt resource file.
  encoding -- Text encoding to use for decoding the data, or None to return binary data.
  """
    qfile = QFile(path)
    try:
        # Open the QFile.
        if not qfile.open(QFile.ReadOnly):
            raise IOError(
                QCoreApplication.translate('QtUtil',
                                           "Failed to open '{}'").format(path))

        # Read the data.
        # TODO: Handle reading in a way that can report errors.
        data = bytes(qfile.readAll())

        if encoding is None:
            return data
        else:
            return data.decode(encoding)

    # Close the QFile.
    finally:
        if qfile.isOpen():
            qfile.close()
Beispiel #15
0
 def loadIcon(self, icon):
     file = QFile(f'icons:{icon}')
     file.open(QFile.ReadOnly)
     self._svgdoc.setContent(file.readAll())
     self._svgdoc.documentElement().setAttribute('fill', self._color)
     file.close()
     self._icon_widget.load(self._svgdoc.toByteArray())
Beispiel #16
0
    def load(self):
        if not QFile.exists(self.filename):
            print ('-------file not exist : ',self.filename)
            return None

        fh = QFile(self.filename)
        if not fh.open(QFile.ReadOnly):
            print ('echec ouverture fichier')
            return None
    
        data = fh.readAll()
    
        codec = QTextCodec.codecForHtml(data)
        unistr = codec.toUnicode(data)
        if QtCore.Qt.mightBeRichText(unistr):
            self.setHtml(unistr)
        else:
            self.setPlainText(unistr)
Beispiel #17
0
 def copyRecursively(self, sourcePath, targetPath):
     srcFileInfo = QFileInfo(sourcePath)
     if srcFileInfo.isDir() and not srcFileInfo.isSymLink():
         targetDir = QDir(targetPath)
         targetDir.cdUp()
         if not targetDir.mkdir(QFileInfo(targetPath).fileName()):
             return False
         fileNames = QDir(sourcePath).entryList(QDir.Files | QDir.Dirs | QDir.NoDotAndDotDot |
                 QDir.Hidden | QDir.System)
         for fileName in fileNames:
             newSourcePath = sourcePath + '/' + fileName
             newTargetPath = targetPath + '/' + fileName
             if not self.copyRecursively(newSourcePath, newTargetPath):
                 return False
     elif not const.OS_WIN and srcFileInfo.isSymLink():
         linkPath = readlink(sourcePath)
         return QFile.link(linkPath, targetPath)
     elif not QFile.copy(sourcePath, targetPath):
         return False
     return True
    def lrelease(self, tsInputFile, qmOutputFile, stripped=True):
        verbose = False
        metTranslations = False
        tor = metaTranslator()

        f = QFile(tsInputFile)
        if not f.open(QtCore.QIODevice.ReadOnly):
            print("lrelease error: Cannot open file '%s'" % tsInputFile)
            return

        t = QTextStream(f)
        fullText = t.readAll()
        f.close()

        if fullText.find("<!DOCTYPE TS>") >= 0:
            if qmOutputFile is None:
                self.releaseTsFile(tsInputFile, verbose, stripped)
            else:
                self.loadTsFile(tor, tsInputFile, verbose)

        else:
            # modId = self.db_.managerModules().idModuleOfFile(tsInputFile)
            key = self.db_.managerModules().shaOfFile(tsInputFile)
            # dir = filedir("../tempdata/cache/%s/%s/file.ts/%s" %
            #               (self._prj.conn.db_name, modId, key))
            tagMap = fullText
            # TODO: hay que cargar todo el contenido del fichero en un diccionario
            for key, value in tagMap:
                toks = value.split(" ")

                for t in toks:
                    if key == "TRANSLATIONS":
                        metTranslations = True
                        self.releaseTsFile(t, verbose, stripped)

            if not metTranslations:
                print(
                    "lrelease warning: Met no 'TRANSLATIONS' entry in project file '%s'" % tsInputFile)

        if qmOutputFile:
            self.releaseMetaTranslator(tor, qmOutputFile, verbose, stripped)
    def _renameSession(self, sessionFilePath='', flags=0):
        if not sessionFilePath:
            action = self.sender()
            if not isinstance(action, QAction):
                return

            sessionFilePath = action.data()

        suggestedName = QFileInfo(sessionFilePath).completeBaseName() + \
            (flags & self.CloneSession) and _('_cloned') or _('_renamed')

        newName, ok = QInputDialog.getText(gVar.app.activeWindow(),
            (flags & self.CloneSession) and _('Clone Session') or _('Rename Session'),
            _('Please enter a new name:'), QLineEdit.Normal, suggestedName)

        if not ok:
            return

        newSessionPath = '%s/%s.dat' % (DataPaths.path(DataPaths.Sessions), newName)
        if QFile.exists(newSessionPath):
            QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                    _('The session file "%s" exists. Please enter another name.') % newName)
            self._renameSession(sessionFilePath, flags)
            return

        if flags & self.CloneSession:
            if not QFile.copy(sessionFilePath, newSessionPath):
                QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                    _('An error occurred when cloning session file.'))
                return
        else:
            if not QFile.rename(sessionFilePath, newSessionPath):
                QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                    _('An error occurred when renaming session file.'))
                return
            if self._isActive(sessionFilePath):
                self._lastActiveSessionPath = newSessionPath
                self._sessionsMetaDataList.clear()
    def _parseTheme(self, path, name):
        '''
        @param: path QString
        @param: name QString
        @return self._Theme
        '''
        info = self._Theme()
        info.isValid = False

        if not QFile(path + 'main.css').exists() or not QFile(
                path + 'metadata.desktop').exists():
            info.isValid = False
            return info

        metadata = DesktopFile('metadata.desktop')
        info.name = metadata.name()
        info.description = metadata.comment()
        info.author = metadata.value('X-App-Author')

        # QString
        iconName = metadata.icon()
        if iconName:
            if QFileInfo.exists(path + iconName):
                info.icon = QIcon(path + iconName)
            else:
                info.icon = QIcon.fromTheme(iconName)

        licensePath = metadata.value('X-App-License')
        if licensePath and QFileInfo.exists(path + licensePath):
            info.license = gVar.appTools.readAllFileContents(path +
                                                             licensePath)

        if not info.name or name in self._themeHash:
            return info

        info.isValid = True
        self._themeHash[name] = info
        return info
    def _sessionMetaData(self, withBackups=True):
        '''
        @brief: return all session meta info list with backup sessions.
        @return: QList<SessionMetaData>
        '''
        self._fillSessionsMetaDataListIfNeeded()

        out = self._sessionsMetaDataList[:]

        if withBackups and QFile.exists(self._firstBackupSession):
            data = self.SessionMetaData()
            data.name = _('Backup 1')
            data.filePath = self._firstBackupSession
            data.isBackup = True
            out.append(data)
        if withBackups and QFile.exists(self._secondBackupSession):
            data = self.SessionMetaData()
            data.name = _('Backup 2')
            data.filePath = self._secondBackupSession
            data.isBackup = True
            out.append(data)

        return out
Beispiel #22
0
    def createFromFile(cls, fpath):
        '''
        @param: fpath QString
        @return: data RestoreData
        '''
        data = RestoreData()
        if not QFile.exists(fpath):
            return data

        recoveryFile = QFile(fpath)
        if not recoveryFile.open(QIODevice.ReadOnly):
            return data

        stream = QDataStream(recoveryFile)

        version = stream.readInt()

        if version == const.sessionVersion:
            byteData = stream.readBytes()
            data = pickle.loads(byteData)
        else:
            print('WARNING: Unsupported session file version', version, 'path',
                  fpath)
        return data
Beispiel #23
0
    def update(self):
        if not prefs['update_metadata'] and not self.reupload:
            self.skipped.emit(self.book_id)
            self.readyForNext.emit(self.index)
            return

        identifiers = self.db.get_proxy_metadata(self.book_id).identifiers
        if not identifiers.get('bookfusion') and not self.reupload:
            self.skipped.emit(self.book_id)
            self.readyForNext.emit(self.index)
            return

        self.req = api.build_request('/uploads/' + identifiers['bookfusion'])
        self.req_body = QHttpMultiPart(QHttpMultiPart.FormDataType)

        if self.reupload:
            self.file = QFile(self.file_path)
            self.file.open(QIODevice.ReadOnly)
            self.req_body.append(self.build_req_part('file', self.file))

        self.append_metadata_req_parts()

        self.reply = self.network.put(self.req, self.req_body)
        self.reply.finished.connect(self.complete_update)
Beispiel #24
0
 def readAllFileByteContents(self, filename):
     '''
     @note: filename maybe resource file like ':/data/bookmarks.json', so must use QFile to read
     @param: filename QString
     @return: QByteArray
     '''
     file_ = QFile(filename)
     if filename and file_.open(QFile.ReadOnly):
         a = file_.readAll()
         file_.close()
         return a.data()
     return b''
    def _saveSession(self):
        '''
        @note: not used yet
        '''
        sessionName, ok = QInputDialog.getText(gVar.app.getWindow(), _('Save Session'),
            _('Please enter a name to save session:'), QLineEdit.Normal,
            _('Saved Session (%s)') % QDateTime.currentDateTime().toString('yyyy MM dd HH-mm-ss'))

        if not ok:
            return

        filePath = '%s/%s.dat' % (DataPaths.path(DataPaths.Sessions), sessionName)
        if QFile.exists(filePath):
            QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                _('The session file "%s" exists. Please enter another name.') % sessionName)
            self._saveSession()
            return

        self.writeCurrentSession(filePath)
Beispiel #26
0
    def _finished(self):
        self._progress(100)

        # File scheme watcher
        if self.url().scheme() == 'file':
            info = QFileInfo(self.url().toLocalFile())
            if info.isFile():
                if not self._fileWatcher:
                    self._fileWatcher = DelayedFileWatcher(self)
                    self._fileWatcher.delayedFileChanged.connect(self._watchedFileChanged)

                filePath = self.url().toLocalFile()

                if QFile.exists(filePath) and filePath not in self._fileWatcher.files():
                    self._fileWatcher.addPath(filePath)
        elif self._fileWatcher and self._fileWatcher.files():
            self._fileWatcher.removePathes(self._fileWatcher.files())

        # AutoFill
        self._autoFillUsernames = gVar.app.autoFill().completePage(self, self.url())
Beispiel #27
0
    def onSaveFile(self):
        '''Save in a file the text description of the graph.'''
        # Export dialog
        result = QFileDialog.getSaveFileName(None, "Export", None,
                                             MainWindowController.dotFilter)

        # Check if Save button has been pressed
        if len(result[0]) > 0:
            filePath = result[0]

            # Create file
            dotFile = QFile(filePath)

            if (not dotFile.open(QIODevice.WriteOnly | QIODevice.Text)):
                QMessageBox.warning(None, "Export", "Export failed.")
            else:
                # Write the text from the TextGraphView into the file
                dotFile.write(
                    QByteArray(self.textGraphController.view.getText().encode(
                        "utf_8")))
            dotFile.close()
Beispiel #28
0
 def removeRecursively(self, filePath):
     '''
     @param: filePath QString
     '''
     fileInfo = QFileInfo(filePath)
     if not fileInfo.exists() and not fileInfo.isSymLink():
         return
     if fileInfo.isDir() and not fileInfo.isSymLink():
         dir_ = QDir(filePath)
         dir_ = dir_.canonicalPath()
         if dir_.isRoot() or dir_.path() == QDir.home().canonicalPath():
             print('CRITICAL: Attempt to remove root/home directory', dir_)
             return False
         fileNames = dir_.entryList(QDir.Files | QDir.Dirs | QDir.NoDotAndDotDot |
                 QDir.Hidden | QDir.System)
         for fileName in fileNames:
             if not self.removeRecursively(filePath + '/' + fileName):
                 return False
         if not QDir.root().rmdir(dir_.path()):
             return False
     elif not QFile.remove(filePath):
         return False
     return True
    def _newSession(self):
        sessionName, ok = QInputDialog.getText(gVar.app.getWindow(), _('New Session'),
            _('Please enter a name to create new session:'), QLineEdit.Normal,
            _('New Session (%s)') % QDateTime.currentDateTime().toString('yyyy MM dd HH-mm-ss'))

        if not ok:
            return

        filePath = '%s/%s.dat' % (DataPaths.path(DataPaths.Sessions), sessionName)
        if QFile.exists(filePath):
            QMessageBox.information(gVar.app.activeWindow(), _('Error!'),
                _('The session file "%1" exists. Please enter another name.') % sessionName)
            self._newSession()
            return

        self.writeCurrentSession(self._lastActiveSessionPath)

        window = gVar.app.createWindow(const.BW_NewWindow)
        for win in gVar.app.windows():
            if win != window:
                win.close()

        self._lastActiveSessionPath = filePath
        self.autoSaveLastSession()
    def load_text(self):
        print("load--csv")
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        dlg.setFilter(QDir.Files)
        if dlg.exec_():
          self.filenames = dlg.selectedFiles()
          print(self.filenames)
          fileDevice = QFile(self.filenames[0])

        if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
          return False
        #f = open(filenames[0], 'r')
        data = []
        #try:
        #print(fileDevice.atEnd())
        while not fileDevice.atEnd():
          #print("a")

          qtBytes = fileDevice.readLine()
          pyBytes = bytes(qtBytes.data())  # QByteArray转换为bytes类型
          lineStr = pyBytes.decode("UTF-8-sig")  # bytes转换为str型
          lineStr = lineStr.strip()  # 去除结尾增加的空行
          data.append(lineStr.split(","))  # 返回QByteArray类型
          #print(qtBytes)
        self.data = data
        print(data[0])
        fileDevice.close()

        localtime = time.localtime(time.time())
        time_s  =time.strftime("%Y-%m-%d %H:%M:%S",localtime)
        s_r = "时间:{}读取文件:{}\n".format(time_s,self.filenames)
        self.logW(s_r)
        #finally:
        #    print("b")
            #self.textEdit2.setText(data)
        self.textEdit.setText("读取成功")
Beispiel #31
0
    def onSaveFile(self):
        '''Save in a file the text description of the graph.'''
        # Export dialog
        result = QFileDialog.getSaveFileName(None, "Export", None,
                                             MainWindowController.dotFilter)

        # Check if Save button has been pressed
        if len(result[0]) > 0:
            filePath = result[0]

            # Create file
            dotFile = QFile(filePath)

            if (not dotFile.open(QIODevice.WriteOnly | QIODevice.Text)):
                QMessageBox.warning(None, "Export", "Export failed.")
            else:
                # Write the text from the TextGraphView into the file
                dotFile.write(QByteArray(self.textGraphController.view
                                             .getText().encode("utf_8")))
            dotFile.close()
Beispiel #32
0
    def showNotification(self, icon, heading, text):
        '''
        @param: icon QPixmap
        @param: heading QString
        @param: text QString
        '''
        if not self._enabled:
            return

        if self._notifType == self.PopupWidget:
            if not self._desktopNotif:
                self._desktopNotif = DesktopNotification()

                def func():
                    self._desktopNotif = None
                self._desktopNotif.closedSignal.connect(func)
            self._desktopNotif.setPixmap(icon)
            self._desktopNotif.setHeading(heading)
            self._desktopNotif.setText(text)
            self._desktopNotif.setTimeout(self._timeout)
            self._desktopNotif.move(self._position)
            self._desktopNotif.show()
        elif self._notifType == self.DesktopNative:
            if const.OS_UNIX and not const.DISABLE_DBUS:
                tmp = QFile(DataPaths.path(DataPaths.Temp) + '/app_notif.png')
                tmp.open(QFile.WriteOnly)
                icon.save(tmp.fileName())

                from PyQt5.Qt import QDBusInterface, QDBusConnection
                dbus = QDBusInterface('org.freedesktop.Notifications', '/org/freedesktop/Notifications',
                        'org.freedesktop.Notifications', QDBusConnection.sessionBus())
                args = []
                args.append('app')
                args.append(self._uint)
                args.append(tmp.fileName())
                args.append(heading)
                args.append(text)
                args.append([])
                args.append({})
                args.append(self._timeout)
                dbus.callWithCallback('Notify', args, self._updateLastId, self._error)
Beispiel #33
0
from PyQt5.QtCore import Qt, QDateTime, QDate

# example qtcharts/examples/datetimeaxis tranlated in python
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    # [1]
    series = QLineSeries()
    # [1]

    # [2]
    # data from http://www.swpc.noaa.gov/ftpdir/weekly/RecentIndices.txt
    # http://www.swpc.noaa.gov/ftpdir/weekly/README
    # http://www.weather.gov/disclaimer
    sunSpots = QFile("sun_spots.txt")
    if not sunSpots.open(QIODevice.ReadOnly | QIODevice.Text):
        sys.exit(1)

    stream = QTextStream(sunSpots)

    while not stream.atEnd():
        line = stream.readLine()

        if line.startswith("#") or line.startswith(":") or line is None:
            continue

        values = line.split()

        day = QDate(int(values[0]), int(values[1]), 15)
Beispiel #34
0
from candlestickdatareader import CandlestickDataReader

# example qtcharts/examples/candlestickchart tranlated in python
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    # [1]
    acmeSeries = QCandlestickSeries()
    acmeSeries.setName("Acme Ltd")
    acmeSeries.setIncreasingColor(QColor("light green"))
    acmeSeries.setDecreasingColor(QColor("red"))
    # [1]

    # [2]  load the data
    acmeData = QFile("acme_data.txt")
    if not acmeData.open(QIODevice.ReadOnly | QIODevice.Text):
        sys.exit(1)

    categories = []
    dataReader = CandlestickDataReader(acmeData)

    while not dataReader.atEnd():
        line = dataReader.read_candlestick_set()
        if line is not None:
            acmeSeries.append(line)
            categories.append(
                QDateTime.fromMSecsSinceEpoch(line.timestamp()).toString("dd"))

    # [2]
Beispiel #35
0
    app.setApplicationName('carmonitor')
    app.setApplicationDisplayName('飞行器遥控️系统')
    app.setApplicationVersion('%d.%d.%d' % (1, 0, 0))

    # translator - system
    translator = QTranslator()
    translator.load(':/lang/qt_' + 'zh_CN')
    app.installTranslator(translator)

    # translator
    translator = QTranslator()
    translator.load(':/lang/' + 'zh_CN')
    app.installTranslator(translator)

    # style sheet
    file = QFile(":/qss/stylesheet-1.qss")
    if file.open(QFile.ReadOnly | QFile.Text):
        app.setStyleSheet(QTextStream(file).readAll())

    app.setFont(QFont('Microsoft Yahei', 15))

    # main window
    mainWidget = MainWidget()
    mainWidget.showMaximized()

        # json string:
    s = json.loads('{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}')
    print(s)
    print(s.keys())
    print(s["name"])
    print(s["type"]["name"])