def askSessionFromUser(self): ''' @return: QString ''' self._fillSessionsMetaDataListIfNeeded() dialog = QDialog(gVar.app.getWindow(), Qt.WindowStaysOnTopHint) label = QLabel(_('Please select the startup session:'), dialog) comboBox = QComboBox(dialog) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, dialog) buttonBox.accepted.connect(dialog.accept) buttonBox.rejected.connect(dialog.reject) layout = QVBoxLayout() layout.addWidget(label) layout.addWidget(comboBox) layout.addWidget(buttonBox) dialog.setLayout(layout) lastActiveSessionFileInfo = QFileInfo(self._lastActiveSessionPath) for metaData in self._sessionsMetaDataList: if QFileInfo(metaData.filePath) != lastActiveSessionFileInfo: comboBox.addItem(metaData.name, metaData.filePath) else: comboBox.insertItem(0, _('%s (last session)') % metaData.name, metaData.filePath) comboBox.setCurrentIndex(0) if dialog.exec_() == QDialog.Accepted: self._lastActiveSessionPath = comboBox.currentData() return self._lastActiveSessionPath
def ensureUniqueFilename(self, name, appendFormat="(%s)"): assert('%s' in appendFormat) info = QFileInfo(name) if not info.exists(): return name # QDir dir_ = info.absoluteDir() # QString fileName = info.fileName() idx = 1 while info.exists(): file_ = fileName index = file_.rfind('.') appendString = appendFormat % idx if index == -1: file_ += appendString else: file_ = file_[:index] + appendString + file_[index:] info.setFile(dir_, file_) idx += 1 return info.absoluteFilePath()
def _isActive(self, filePathOrFileInfo): ''' @param: filePath QString @param: fileInfo QFileInfo ''' if isinstance(filePathOrFileInfo, QFileInfo): fileInfo = filePathOrFileInfo else: # must be QString fileInfo = QFileInfo(filePathOrFileInfo) return fileInfo == QFileInfo(self._lastActiveSessionPath)
def load_icon(self, fileinfo): key = 'default' icons = self.icons if fileinfo.isSymLink(): if not fileinfo.exists(): return icons['zero'] fileinfo = QFileInfo(fileinfo.readLink()) if fileinfo.isDir(): key = 'dir' else: ext = unicode(fileinfo.completeSuffix()).lower() key = self.key_from_ext(ext) return self.cached_icon(key)
def printPDF(self): fn, _ = QFileDialog.getSaveFileName(self, 'Export PDF', None, 'PDF files (.pdf);;All Files()') if fn != '': if QFileInfo(fn).suffix() == "": fn += '.pdf' printer = QPrinter(QPrinter.HighResolution) #printer.setPageMargins(QMarginF(0, 0, 0, 0)) printer.setFullPage(True) printer.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) self.textEdit.document().print_(printer) # App = QApplication(sys.argv) # window = Window() # # fixed_font = QFont("monospace") # # fixed_font.setStyleHint(QFont.TypeWriter) # # window.textEdit.setFont(fixed_font) # from printdocument import * # window.textEdit.setText(getdocument()) # sys.exit(App.exec())
def getSaveFileName(self, name, parent=None, caption='', dir_='', filter_='', selectedFilter='', options=QFileDialog.Options()): ''' @param: name QString @param: parent QWidget @param: caption QString @param: dir_ QString @param: filter_ QString @param: selectedFilter QString TODO: this is an output parameter @param: options QFileDialog::Options @return: QString ''' settings = Settings() settings.beginGroup('FileDialogPaths') lastDir = settings.value(name, '') fileName = self.getFileName(dir_) if not lastDir: lastDir = dir_ else: lastDir = pathjoin(lastDir, fileName) path, selectedFilter = QFileDialog.getSaveFileName(parent, caption, lastDir, filter_, selectedFilter, options) if path: settings.setValue(name, QFileInfo(path).absolutePath()) settings.endGroup() return path
def _openSession(self, sessionFilePath='', flags=0): if not sessionFilePath: action = self.sender() if not isinstance(action, QAction): return sessionFilePath = action.data() if self._isActive(sessionFilePath): return sessionData = RestoreData() sessionData = RestoreManager.createFromFile(sessionFilePath) if not sessionData.isValid(): return # BrowserWindow window = gVar.app.getWindow() if flags & self.SwitchSession: self.writeCurrentSession(self._lastActiveSessionPath) window = gVar.app.createWindow(const.BW_OtherRestoredWindow) for win in gVar.app.windows(): if win != window: win.close() if not (flags & self.ReplaceSession): self._lastActiveSessionPath = QFileInfo(sessionFilePath).canonicalFilePath() self._sessionsMetaDataList.clear() gVar.app.openSession(window, sessionData)
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)
def export_pdf(self): fn, _ = QFileDialog.getSaveFileName(self, 'Export PDF', None, 'PDF files (.pdf);;All Files()') if fn != '': if QFileInfo(fn).suffix() == "": fn += '.pdf' for self.i in range(3): self.shown[self.i] = 1 if self.timer[self.i] != 0: self.timer[self.i].stop() self.spectros[self.i].hide() if self.signals[self.i] != 0: self.graphs[self.i].show() self.spectros[self.i].show() printer = QPrinter(QPrinter.HighResolution) printer.setOrientation(1) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) painter = QtGui.QPainter(printer) pixmap = QtWidgets.QWidget.grab(self.centralwidget).scaled( printer.pageRect(QPrinter.DevicePixel).size().toSize(), QtCore.Qt.KeepAspectRatio) painter.drawPixmap(0, 0, pixmap) painter.end() self.view_start() if self.action1_Signal.isChecked(): self.graphs[0].show() if self.action2_Signals.isChecked(): self.graphs[1].show() if self.action3_Signals.isChecked(): self.graphs[2].show()
def iconFromFileName(self, fileName): ''' @param: fileName QString @return: QIcon ''' tempInfo = QFileInfo(fileName) suffix = tempInfo.suffix() if suffix in self._s_iconCache: return self._s_iconCache[suffix] iconProvider = QFileIconProvider() tempFile = DataPaths.path(DataPaths.Temp) + '/XXXXXX.' + suffix tempFile.open() tempInfo.setFile(tempFile.fileName()) icon = QIcon(iconProvider.icon(tempInfo)) self._s_iconCache[suffix] = icon
def printPDF(self): fn, _ = QFileDialog.getSaveFileName(self, 'Export PDF', None, 'PDF files (.pdf);;All Files()') if fn != '': if QFileInfo(fn).suffix() == "" : fn += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) self.plainTextEdit.document().print_(printer)
def reload_url(self): self.tableWidget.not_start = True self.df = self.tableWidget.load_data_from_db() render_df_html(self.df) # 高分屏自适应 html_path = "./pie_base.html" html_path = QFileInfo(html_path).absoluteFilePath() self.url = QUrl("file:///" + html_path) self.view.load(self.url)
def printPDF(self): fn, _ = QFileDialog.getSaveFileName(self, 'Exportar PDF', None, \ 'Archivos PDF (.pdf);;Todos los Archivos()') if fn != '': if QFileInfo(fn).suffix() == "": fn += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) self.textEdit.document().print_(printer)
def exportPDF(self): file, _ = QFileDialog.getSaveFileName(self, 'Export PDF', None, 'PDF files (.pdf);;All Files()') if file != "": if QFileInfo(file).suffix() == "": file += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(file) self.textedit.document().print_(printer)
def _optimizeDb(self): gVar.app.setOverrideCursor(Qt.WaitCursor) profilePath = DataPaths.currentProfilePath() sizeBefore = gVar.appTools.fileSizeToString( QFileInfo(profilePath + 'browserdata.db').size()) IconProvider.instance().clearOldIconsInDatabase() sizeAfter = gVar.appTools.fileSizeToString( QFileInfo(profilePath + 'browserdata.db').size()) gVar.app.restoreOverrideCursor() QMessageBox.information( self, _('Database Optimized'), _('Database successfully optimized.<br/><br/><b>Database Size Before: </b>%s<br/><b>Database Size After: </b>%s' ) % # noqa E501 (sizeBefore, sizeAfter))
def Book_Export_Report(self): # export books data to excel file self.cur.execute(''' SELECT code, title, category_id, author_id, price FROM books ''') data = self.cur.fetchall() self.cur.execute(''' SELECT price FROM books ''') data2 = self.cur.fetchall() # Pdf fn, _ = QFileDialog.getSaveFileName(self, 'Export PDF', None, 'PDF file (.pdf);;All Files()') if fn != '': if QFileInfo(fn).suffix() == "": fn += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) data2.document().print_(printer) excel_file = Workbook('books_Report.xlsx') sheet1 = excel_file.add_worksheet() sheet1.write(0, 0, "Book Code") sheet1.write(0, 1, "Book Title") sheet1.write(0, 2, "Category") sheet1.write(0, 3, "Author") sheet1.write(0, 4, "Price") row_number = 1 for row in data: column_number = 0 for item in row: sheet1.write(row_number, column_number, str(item)) column_number += 1 row_number += 1 row_number = 1 # كود من ابداعاتي لحساب مجموع المبيعات sum = 0 for row in data2: column_number = 0 for item in row: sum = sum + item column_number += 1 row_number += 1 row_number += 1 sheet1.write(row_number, 0, "Total") sheet1.write(row_number, 1, str(sum)) # excel_file.close() self.statusBar().showMessage('تم إنشاء التقرير بنجاح بنجاح')
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())
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 _save_pdf(self): # pragma: no cover filename = QFileDialog().getSaveFileName( self, self.tr("Export document to PDF"), "", self.tr("PDF files (*.pdf)"), options=QFileDialog.ShowDirsOnly)[0] if filename: if not QFileInfo(filename).suffix(): filename += ".pdf" printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setColorMode(QPrinter.Color) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) self._doc.text.print_(printer)
def run(self): file = QFileInfo(self.sourcePath) lines = [ file.path() + '/' + line.rstrip('\n') for line in open(file.absoluteFilePath()) ] self.newText.emit( '--------------------------------------------------------------------------------' ) self.newText.emit('Now copying {} files.'.format(len(lines))) count = 1 for x in lines: if QFileInfo(x).exists(): y = self.destinationPath + '/IMG_' + "{:04}".format( count) + '.' + QFileInfo(x).suffix() self.newText.emit('copying {} to {}'.format(x, y)) copyfile(x, y) count = count + 1 else: mList = glob.glob(file.path() + '/**/' + os.path.basename(x), recursive=True) if 1 == len(mList): # Found 1 file we will use this one x = mList[0] y = self.destinationPath + '/IMG_' + "{:04}".format( count) + '.' + QFileInfo(x).suffix() self.newText.emit('copying {} to {}'.format(x, y)) copyfile(x, y) count = count + 1 elif 0 == len(mList): self.newText.emit( 'File {} could not be found, will be skipped.'.format( x)) else: self.newText.emit( 'Multiple files for {} have been found, file will be skipped.' .format(x)) if (len(lines) != count - 1): self.newText.emit('Warning: Could not copy all files!') self.newText.emit('Finished copying {} files of {}'.format((count - 1), len(lines))) self.newText.emit( '--------------------------------------------------------------------------------' )
def _fillSessionsMetaDataListIfNeeded(self): ''' @brief: load all session meta info from sessions directory include default session file ''' if self._sessionsMetaDataList: return dir_ = QDir(DataPaths.path(DataPaths.Sessions)) sessionFiles = [] sessionFiles.append(QFileInfo(self.defaultSessionPath())) sessionFiles.extend(dir_.entryInfoList(['*.*'], QDir.Files, QDir.Time)) fileNames = [] defaultFileInfo = QFileInfo(self.defaultSessionPath()) for fileInfo in sessionFiles: if not RestoreManager.validateFile(fileInfo.absoluteFilePath()): continue metaData = self.SessionMetaData() metaData.name = baseName = fileInfo.completeBaseName() if fileInfo == defaultFileInfo: metaData.name = _('Default session') metaData.isDefault = True elif baseName in fileNames: metaData.name = fileInfo.fileName() if self._isActive(fileInfo): metaData.isActive = True fileNames.append(metaData.name) metaData.filePath = fileInfo.canonicalFilePath() self._sessionsMetaDataList.append(metaData)
def save_file(self): if self.validate(): self.clear_file_error() filepath = str(self.file_path_tview.text()) fileinfo = QFileInfo(filepath) filename = str(int(time.time())) + "_" + fileinfo.fileName() keyboard_name = "Unknown" with open(filepath, encoding="utf-8") as search: for line in search: line = line.rstrip() # remove '\n' at end of line if "NAME" in line: name_line = line name_list = name_line.split('=', 1) if len(name_list) > 0: keyboard_name = name_list[1] if keyboard_name == "Unknown": self.show_file_error("SCIM table name header not found") elif DatabaseManager.check_keyboard_exist(keyboard_name): self.show_file_error("Keyboard already exists") else: shutil.copyfile(filepath, self.table_path + "\\" + filename) DatabaseManager.add_keyboard(keyboard_name, filename) self.file_path_tview.setText("") self.update_table()
def save_file(self): if self.validate(): self.clear_file_error() filepath = str(self.file_path_tview.text()) fileinfo = QFileInfo(filepath) filename = str(int(time.time())) + "_" + fileinfo.fileName() keyboard_name = "Unknown" with open(filepath, encoding="utf-8") as search: for line in search: line = line.rstrip() # remove '\n' at end of line if "NAME" in line: name_line = line name_list = name_line.split('=', 1) if len(name_list) > 0: keyboard_name = name_list[1] if keyboard_name == "Unknown": self.show_file_error("SCIM table name header not found") elif DatabaseManager.check_keyboard_exist(keyboard_name): self.show_file_error("Keyboard already exists") else: shutil.copyfile(filepath, self.table_path + "\\" + filename) DatabaseManager.add_keyboard(keyboard_name, self.table_path + "\\" + filename) self.file_path_tview.setText("") self.update_table()
def _refresh(self): self._ui.treeWidget.clear() sessions = gVar.app.sessionManager()._sessionMetaData() for session in sessions: item = QTreeWidgetItem() item.setText(0, session.name) item.setText(1, QFileInfo(session.filePath).lastModified().toString(Qt.DefaultLocaleShortDate)) item.setData(0, self._SessionFileRole, session.filePath) item.setData(0, self._IsBackupSessionRole, session.isBackup) item.setData(0, self._IsActiveSessionRole, session.isActive) item.setData(0, self._IsDefaultSessionRole, session.isDefault) self._updateItem(item) self._ui.treeWidget.addTopLevelItem(item) self._updateButtons()
def build_req_part(self, name, value): part = QHttpPart() part.setHeader(QNetworkRequest.ContentTypeHeader, None) if isinstance(value, QFile): filename = QFileInfo(value).fileName() part.setHeader( QNetworkRequest.ContentDispositionHeader, 'form-data; name="{}"; filename="{}"'.format( self.escape_quotes(name), self.escape_quotes(filename))) part.setBodyDevice(value) else: part.setHeader( QNetworkRequest.ContentDispositionHeader, 'form-data; name="{}"'.format(self.escape_quotes(name))) part.setBody(value.encode('utf-8')) return part
def getExistingDirectory(self, name, parent=None, caption='', dir_='', options=QFileDialog.ShowDirsOnly): ''' @param: name QString @param: parent QWidget @param: caption QString @param: dir_ QString @param: options QFileDialog.Options @return: QString ''' settings = Settings() settings.beginGroup('FileDialogPaths') lastDir = settings.value(name, dir_) path = QFileDialog.getExistingDirectory(parent, caption, lastDir, options) if path: settings.setValue(name, QFileInfo(path).absolutePath()) settings.endGroup() return path
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 _web_init(self): render_df_html(self.df) self.view = QWebEngineView() # self.scrollArea.setWidget(self.view) # todo 尺寸修改 # self.view.resize(self.label.width(), self.label.height()) # print(self.scrollAreaWidgetContents.geometry()) # self.view.setGeometry(self.scrollAreaWidgetContents.geometry()) self.view.resize(800, 800) # print(self.scrollArea.geometry()) # print(self.view.geometry()) # self.index = './data/template.html' # self.index = "./mytest/render.html" # self.index = "./mytest/pie_set_color.html" # self.index = "./mytest/pie_base.html" self.index = "./pie_base.html" # self.index = "./template.html" # self.index = "./mytest/multiple_pie.html" html_path = QFileInfo(self.index).absoluteFilePath() # print(html_path) self.url = QUrl("file:///" + html_path) self.view.load(self.url) self.scrollArea.setWidget(self.view)
def startDownloading(self): self._download.finished.connect(self._finished) self._download.downloadProgress.connect(self._downloadProgress) self._downloading = True if self._downTimer.elapsed() < 1: # TODO: ? self._downTimer.start() self._updateDownloadInfo(0, self._download.receivedBytes(), self._download.totalBytes()) if const.OS_LINUX: # QFileIconProvider uses only suffix on Linux iconProvider = QFileIconProvider() # QIcon fileIcon = iconProvider.icon(QFileInfo(self._fileName)) if not fileIcon.isNull(): self._ui.fileIcon.setPixmap(fileIcon.pixmap(30)) else: self._ui.fileIcon.setPixmap(self.style().standardIcon( QStyle.SP_FileIcon).pixmap(30)) else: self._ui.fileIcon.hide()
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 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