def create_progress_bar(self, title): progress = QProgressDialog(self) progress.setAutoClose(False) progress.setWindowTitle(title) progress.setCancelButton(None) progress.setWindowModality(Qt.WindowModal) return progress
def draw_progress_dialog(self): d = QProgressDialog('Обработка битых ссылок', 'Отмена', 0, 0) d.setWindowModality(Qt.WindowModal) d.setCancelButton(None) d.setWindowTitle('Обработка битых ссылок') d.setMaximumWidth(500) return d
def __init__(self, parent=None): QProgressDialog.__init__(self, parent) self.progress = QProgressBar(self) self.progress.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.setBar(self.progress)
def waitForSignal(signal, message="", timeout=0): """Waits (max timeout msecs if given) for a signal to be emitted. It the waiting lasts more than 2 seconds, a progress dialog is displayed with the message. Returns True if the signal was emitted. Return False if the wait timed out or the dialog was canceled by the user. """ loop = QEventLoop() dlg = QProgressDialog(minimum=0, maximum=0, labelText=message) dlg.setWindowTitle(appinfo.appname) dlg.setWindowModality(Qt.ApplicationModal) QTimer.singleShot(2000, dlg.show) dlg.canceled.connect(loop.quit) if timeout: QTimer.singleShot(timeout, dlg.cancel) stop = lambda: loop.quit() signal.connect(stop) loop.exec_() signal.disconnect(stop) dlg.hide() dlg.deleteLater() return not dlg.wasCanceled()
def build_iso(self, directory, iso_file): if self.process: return directory = os.path.abspath(directory) iso_file = os.path.abspath(iso_file) self.progress = QProgressDialog("Building ISO...", QtCore.QString(), 0, 0, self.parent) self.progress.setWindowTitle("Building ISO") self.progress.setWindowModality(Qt.Qt.WindowModal) self.progress.setAutoClose(False) self.progress.setMinimumDuration(1000) self.progress.show() self.progress.setValue(0) self.progress.setMaximum(100) self.process = QProcess() self.process.finished.connect(self.__build_finished) self.process.setReadChannel(QProcess.StandardError) self.process.readyRead.connect(self.__parse_output) self.process.start("tools/mkisofs", [ "-sort", "data/file_order.txt", "-iso-level", "4", "-xa", "-A", "PSP GAME", "-V", "DANGANRONPA", "-sysid", "PSP GAME", "-volset", "DANGANRONPA", "-p", "SPIKE", "-publisher", "SPIKE", "-o", iso_file, directory ])
def createProgress(self, title): progress = QProgressDialog(title, "Abort", 0, 10) progress.setAttribute(Qt.WA_DeleteOnClose) progress.setAutoClose(True) progress.setMinimumDuration(500) progress.setValue(0) return progress
def __init__(self, report_title, org_name, db, iface, file_path=None): self.report_title = report_title.upper() self.db = db self.iface = iface self.org_name = org_name.upper() self.user = "******" self.file_path = file_path self.report_file = None self.start_point = QgsPoint() self.end_point = QgsPoint() self.esu_layer = QgsMapLayerRegistry.instance().mapLayersByName( 'ESU Graphic')[0] self.poly_layer = QgsMapLayerRegistry.instance().mapLayersByName( 'Road Polygons')[0] self.filter = None self.queries = {} self.headers = {} self.headers_no_items = {} self.column_names = {} self.init_headers() self.init_queries() self.validation_dia = None self.progress_win = None self.progress_win = QProgressDialog("", None, 0, 13, self.validation_dia) self.progress_win.setFixedSize(380, 100) self.progress_win.setModal(True) self.progress_win.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint) self.progress_win.setWindowTitle("Export Validation Report")
def addMediaFile(self): path = '.' filename = self.labeltool.getCurrentFilename() if (filename is not None) and (len(filename) > 0): path = QFileInfo(filename).path() image_types = [ '*.jpg', '*.bmp', '*.png', '*.pgm', '*.ppm', '*.ppm', '*.tif', '*.gif' ] video_types = [ '*.mp4', '*.mpg', '*.mpeg', '*.avi', '*.mov', '*.vob' ] format_str = ' '.join(image_types + video_types) fnames = QFileDialog.getOpenFileNames(self, "%s - Add Media File" % APP_NAME, path, "Media files (%s)" % (format_str, )) item = None numFiles = len(fnames) progress_bar = QProgressDialog('Importing files...', 'Cancel import', 0, numFiles, self) for fname,c in zip(fnames, range(numFiles)): if len(str(fname)) == 0: continue fname = str(fname) if os.path.isabs(fname): fname = os.path.relpath(fname, str(path)) for pattern in image_types: if fnmatch.fnmatch(fname, pattern): item = self.labeltool.addImageFile(fname) progress_bar.setValue(c) if item is None: return self.labeltool.addVideoFile(fname) progress_bar.close() return item
def setLabelText(self, text): # TODO: the limit should depend on the rendered size and not on the # number of chars. if len(text) > 40: QProgressDialog.setLabelText(self, "..." + text[-37:]) else: QProgressDialog.setLabelText(self, text)
def progress(data, *args): """ A very pythonic progress dialog. Iterate over progress(iterator) instead of iterator. That’s pretty much it. """ # found at http://lateral.netmanagers.com.ar/weblog/posts/BB917.html # © 2000-2012 Roberto Alsina # Creative Commons Attribution-NonCommercial-ShareAlike 2.5 licence # http://creativecommons.org/licenses/by-nc-sa/2.5/ # Added check for qt. RAS 2013-01-13 it = iter(data) if with_anki: widget = QProgressDialog(*args + (0, it.__length_hint__())) c = 0 for v in it: if with_anki: QCoreApplication.instance().processEvents() if widget.wasCanceled(): raise StopIteration c += 1 widget.setValue(c) yield (v)
def run(self): if self._configuration: try: self._configuration.check_all() self._reinit_simu() self._progress_bar = QProgressDialog("Simulating...", "Abort", 0, 100) self._progress_bar.canceled.connect(self.abort) self._progress_bar.show() self.worker = RunSimulation() self._model = Model(self._configuration, callback=self.worker.updateProgressBar) self.worker.set_model(self._model) self.worker.finished.connect(self.runFinished) self.worker.start() QObject.connect(self.worker, SIGNAL("updateProgressBar"), self.updateProgressBar) except Exception as msg: QMessageBox.warning(self, "Configuration error", str(msg)) self._reinit_simu() self.runFinished()
def __init__(self, parent=None, **kwargs): super(AddonManagerDialog, self).__init__(parent, **kwargs) self.setLayout(QVBoxLayout()) self.addonwidget = AddonManagerWidget() self.addonwidget.layout().setContentsMargins(0, 0, 0, 0) self.layout().addWidget(self.addonwidget) buttons = QDialogButtonBox(orientation=Qt.Horizontal, standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttons.accepted.connect(self.__accepted) buttons.rejected.connect(self.reject) self.layout().addWidget(buttons) self.__progress = QProgressDialog( self, Qt.Sheet, minimum=0, maximum=0, labelText=self.tr("Retrieving package list"), sizeGripEnabled=False, windowTitle="Progress") self.__progress.canceled.connect(self.reject) # The installer thread self.__thread = None # The installer object self.__installer = None
def __init__(self, parent=None, iface=None): """Constructor for import dialog. .. versionadded: 3.3 :param parent: Optional widget to use as parent. :type parent: QWidget :param iface: An instance of QGisInterface. :type iface: QGisInterface """ QDialog.__init__(self, parent) self.parent = parent self.setupUi(self) title = self.tr('PetaBencana Downloader') self.setWindowTitle(title) icon = resources_path('img', 'icons', 'add-petabencana-layer.svg') self.setWindowIcon(QtGui.QIcon(icon)) self.iface = iface self.source = None self.radio_button_group = QButtonGroup() self.radio_button_group.addButton(self.radio_button_production) self.radio_button_group.addButton(self.radio_button_development) self.radio_button_group.setExclusive(True) self.radio_button_production.setChecked(True) self.populate_combo_box() developer_mode = setting('developer_mode', False, bool) if not developer_mode: self.radio_button_widget.hide() self.source_label.hide() self.output_group.adjustSize() # signals self.radio_button_production.clicked.connect(self.populate_combo_box) self.radio_button_development.clicked.connect(self.populate_combo_box) # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) self.progress_dialog.setWindowTitle(title) # Set up things for context help self.help_button = self.button_box.button(QtGui.QDialogButtonBox.Help) # Allow toggling the help button self.help_button.setCheckable(True) self.help_button.toggled.connect(self.help_toggled) self.main_stacked_widget.setCurrentIndex(1) # set up the validator for the file name prefix expression = QRegExp('^[A-Za-z0-9-_]*$') validator = QRegExpValidator(expression, self.filename_prefix) self.filename_prefix.setValidator(validator) self.time_stamp = None self.restore_state()
def __init__(self, parent=None, iface=None): """Constructor for import dialog. :param parent: Optional widget to use as parent :type parent: QWidget :param iface: An instance of QGisInterface :type iface: QGisInterface """ QDialog.__init__(self, parent) self.parent = parent self.setupUi(self) self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader')) self.iface = iface self.url = "http://osm.linfiniti.com/buildings-shp" # creating progress dialog for download self.progressDialog = QProgressDialog(self) self.progressDialog.setAutoClose(False) myTitle = self.tr("InaSAFE OpenStreetMap Downloader") self.progressDialog.setWindowTitle(myTitle) self.show_info() self.network_manager = QNetworkAccessManager(self) self.restore_state() self.update_extent()
def __init__(self, parent=None, iface=None): """Constructor for import dialog. :param parent: Optional widget to use as parent :type parent: QWidget :param iface: An instance of QGisInterface :type iface: QGisInterface """ QDialog.__init__(self, parent) self.parent = parent self.setupUi(self) self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader')) self.iface = iface self.buildings_url = 'http://osm.linfiniti.com/buildings-shp' self.building_points_url = \ 'http://osm.linfiniti.com/building-points-shp' self.roads_url = 'http://osm.linfiniti.com/roads-shp' self.help_context = 'openstreetmap_downloader' # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) title = self.tr('InaSAFE OpenStreetMap Downloader') self.progress_dialog.setWindowTitle(title) # Set up context help help_button = self.button_box.button(QtGui.QDialogButtonBox.Help) help_button.clicked.connect(self.show_help) self.show_info() # set up the validator for the file name prefix expression = QRegExp('^[A-Za-z0-9-_]*$') validator = QRegExpValidator(expression, self.filename_prefix) self.filename_prefix.setValidator(validator) # Set Proxy in webpage proxy = get_proxy() self.network_manager = QNetworkAccessManager(self) if proxy is not None: self.network_manager.setProxy(proxy) self.restore_state() # Setup the rectangle map tool self.canvas = iface.mapCanvas() self.rectangle_map_tool = \ RectangleMapTool(self.canvas) self.rectangle_map_tool.rectangle_created.connect( self.update_extent_from_rectangle) self.button_extent_rectangle.clicked.connect( self.drag_rectangle_on_map_canvas) # Setup pan tool self.pan_tool = QgsMapToolPan(self.canvas) self.canvas.setMapTool(self.pan_tool) self.update_extent_from_map_canvas()
def __init__(self, parent): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QProgressDialog.__init__(self, '', "Cancel", 0, 100, parent, flags) self.setModal(True) self.setAutoReset(False) self.setAutoClose(False) self._timer = QTimer() self._jobid = '' self._timer.timeout.connect(self.updateProgress)
def __init__(self, parent): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QProgressDialog.__init__(self, '', "Cancel", 0, 100, parent, flags) self.setModal(True) self.setAutoReset(False) self.setAutoClose(False) self._timer = QTimer() self._jobid = '' self._timer.timeout.connect(self.updateProgress)
def loadFile(self): mnFileName = unicode(self.mnFileNameInput.text()) if not mnFileName: QMessageBox.warning(glb.mainWin, QCoreApplication.translate('SmileKit', 'No filename specified'), QCoreApplication.translate('SmileKit', 'Please enter a filename in the input box!')) return progressDlg = QProgressDialog(glb.mainWin) progressDlg.setRange(0, 100) progressDlg.setLabelText('Reading File...') progressDlg.show() a = glb.application def progFunc(p): progressDlg.setValue(p) if a.hasPendingEvents(): a.processEvents() r = readMnFile(mnFileName, progress=progFunc) self.data = r progressDlg.close() self.locationFrame.setEnabled(1) self.statisticsFrame.setEnabled(1) if ncOk: self.ncFileFrame.setEnabled(1) self.statisticsButton.setCheckState(Qt.Unchecked) self.locNameInput.setText(r['name']) c = unicode(QCoreApplication.translate('SmileKit', "created %s from %s by Meteo2Nc.py (v%d)")) self.locCommentInput.setText(c % (time.ctime(), mnFileName, version)) self.locLatitudeInput.setValue(r['latitude']) self.locLongitudeInput.setValue(r['longitude']) self.locHeightInput.setValue(r['height']) self.locTimeZoneInput.setValue(r['timezone']) path, tmp = os.path.split(mnFileName) ncFileName = os.path.join(path, makeFileName(r['name'])+'_weather.nc') self.ncFileNameInput.setText(ncFileName)
def menu_file_save_stack(self): "Processes the entire current stack, and saves as a new name" name=QtGui.QInputDialog.getText(None,"Enter Filename","Enter an output filename for the entire processed particle stack (not just the displayed images).") if not name[1] : return # canceled allfilt=" ".join([i.getAsProc() for i in self.processorlist]) n=EMUtil.get_image_count(self.datafile) from PyQt4.QtGui import QProgressDialog progressdialog=QProgressDialog("Processing Images","Abort",0,n,self) progressdialog.setMinimumDuration(1000) e=E2init(["e2proc2d.py",self.datafile,str(name[0]),allfilt]) # we don't actually run this program, since we couldn't have a progress dialog easo;y then pp=[i.processorParms() for i in self.processorlist] for i in xrange(n): im=EMData(self.datafile,i) QtGui.qApp.processEvents() for p in pp: im.process_inplace(p[0],p[1]) im.write_image(str(name[0]),i) progressdialog.setValue(i+1) if progressdialog.wasCanceled() : print "Processing Cancelled" break progressdialog.setValue(n) E2end(e)
def create_progress_bar(self, title): progress = QProgressDialog(self) progress.setAutoClose(False) progress.setWindowTitle(title) progress.setCancelButton(None) progress.setWindowModality(Qt.WindowModal) return progress
def init_game_tree(self, mainAppWindow = None): # ugly workaround: # the next lines are just to ensure that # the "board cache" (see doc. of python-chess lib) # is initialized. The call to the last board of the main # line ensures recursive calls to the boards up to the root # # if a mainAppWindow is passed, a progress bar # will be displayed while the game tree is initialized # the app might "freeze" otherwise, as longer games # i.e. (> 70 moves) can take some time to initialize temp = self.current.root() end = self.current.end() mainline_nodes = [temp] while(not temp == end): temp = temp.variations[0] mainline_nodes.append(temp) cnt = len(mainline_nodes) if(not mainAppWindow == None): pDialog = QProgressDialog(mainAppWindow.trUtf8("Initializing Game Tree"),None,0,cnt,mainAppWindow) pDialog.setWindowModality(Qt.WindowModal) pDialog.show() QApplication.processEvents() for i,n in enumerate(mainline_nodes): QApplication.processEvents() pDialog.setValue(i) if(i > 0 and i % 25 == 0): _ = n.cache_board() pDialog.close() else: QApplication.processEvents() for i,n in enumerate(mainline_nodes): if(i > 0 and i % 25 == 0): _ = n.cache_board()
def createProgress(self, title): progress = QProgressDialog(title, "Abort", 0, 10) progress.setAttribute(Qt.WA_DeleteOnClose) progress.setAutoClose(True) progress.setMinimumDuration(500) progress.setValue(0) return progress
def __init__(self, parent = None): QProgressDialog.__init__(self, parent) self.setWindowTitle(_("Downloading")) # Top level fixed size dialog self.setWindowModality(Qt.WindowModal) # Do not close when reaching 100% self.setAutoClose(False) self.setAutoReset(False) self.__nbr_pages_ = -1
def progressDialog(self, count): """ Создаёт QProgressDialog с нужными параметрами для индикации процесса общения с сервером """ # Добавление пробелов в начало и конец позволяет задать нужный размер диалога. По-другому # не нашёл как label = "{}{}{}".format(' '*20, 'Отмечаем записи, как прочитанные', ' '*20) progress = QProgressDialog(label, 'Отмена', 0, count, self) progress.setWindowModality(Qt.WindowModal) progress.setWindowTitle('Общение с сервером') return progress
def __init__(self, parent): """ Initializes the progress dialog of the template updater with the option of updating the label of the dialog. :return: :rtype: """ QProgressDialog.__init__(self, parent) self.title = None self.prog = None
def __init__(self, left, top, right, bottom, csv_filename, username, password, client_id, client_secret, days_to_query=60): self.left = left self.top = top self.right = right self.bottom = bottom self.csv_filename = csv_filename self.days_to_query = days_to_query self.begin_date = None self.end_date = None self.username = username self.password = password self.client_id = client_id self.client_secret = client_secret # throw up a progress dialog min_progress = 0.0 max_progress = ((self.right - self.left) / INCREMENTAL_INTERVAL) * \ ((self.top - self.bottom) / INCREMENTAL_INTERVAL) self.current_progress = min_progress self.progress_dialog = QProgressDialog("Building up CSV file", "Abort", int(min_progress), int(max_progress), None) self.progress_dialog.setCancelButton(None) self.progress_dialog.setWindowTitle("CSV Output") self.progress_dialog.setLabelText("Building up CSV file") self.progress_dialog.setMinimumDuration(0) self.progress_dialog.setValue(0) self.progress_dialog.show() self.csv_elements = [] self.csv_generator_object = CSVGeneratorObject(self) self.vector_header_dict = {} self.pool = QThreadPool() self.finished_submissions = False self.lock = Lock()
def __init__(self, parent): """ Initializes the progress dialog of the template updater with the option of updating the label of the dialog. :return: :rtype: """ QProgressDialog.__init__(self, parent) self.title = None self.prog = None
def accept(self): model = self.selectedimages_model filename = path(self.ui.savePath.text()) if not filename: QMessageBox.critical(self, "Error in processing", "You have to provide a file name to save the computation in.") return if not filename.dirname().exists(): QMessageBox.critical(self, "Error in processing", "The directory containing the file path provided do not exist.\nPlease create the directory or provide a path in an existing directory.") return if not model: QMessageBox.critical(self, "Error in processing", "You didn't any image to compute the growth with.") return if self.resample == 0: if self.method == "Forward": method = growth_computation_methods.ForwardMethod() elif self.method == "Backward": method = growth_computation_methods.BackwardMethod() elif self.method == "Start": method = growth_computation_methods.StartMethod() else: if self.method == "Forward": method = growth_computation_methods.ForwardDenseMethod(self.resample) elif self.method == "Backward": method = growth_computation_methods.BackwardDenseMethod(self.resample) elif self.method == "Start": method = growth_computation_methods.StartDenseMethod(self.resample) use_daughters = self.ui.daughterCells.isChecked() if self.cells_selection == "AddPoints": cells_selection = growth_computation_methods.AddPointsSelection(use_daughters, self.ui.maxVariationAddPoints.value()/100.) elif self.cells_selection == "AllCells": if self.withVariation: cells_selection = growth_computation_methods.AllCellsSelection(use_daughters, self.ui.maxVariationAllCells.value()/100.) else: cells_selection = growth_computation_methods.AllCellsSelection(use_daughters, None) elif self.cells_selection == "FullCells": cells_selection = growth_computation_methods.FullCellsOnlySelection(use_daughters) else: raise "Cells selection method '%s' is not implemented" % self.cells_selection thread = GrowthComputationThread(self) thread.data = self.data thread.list_img = model.names thread.method = method thread.cells_selection = cells_selection thread.filename = filename self.thread = thread nb_images = thread.nbOutputImages() progress = QProgressDialog("Computing the growth on %d images" % nb_images, "Abort", 0, nb_images-1, self) progress.setMinimumDuration(2000) self.progress = progress progress.canceled.connect(thread.stop) thread.start()
def init_from_pgn(self, mainWindow, msg): with open(self.filename) as pgn: size = os.path.getsize(self.filename) self.entries = [] pDialog = QProgressDialog(msg, None, 0, size, mainWindow) pDialog.show() pDialog.setWindowModality(PyQt4.QtCore.Qt.WindowModal) QApplication.processEvents() for offset, headers in chess.pgn.scan_headers(pgn): QApplication.processEvents() pDialog.setValue(offset) self.entries.append(Entry(offset, headers)) pDialog.close() self.checksum = crc32_from_file(self.filename)
def __init__(self, parent, model): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint QProgressDialog.__init__(self, '', "Cancel", 0, 100, parent, flags) self.model = model model.view = self # We don't have access to QProgressDialog's labels directly, so we se the model label's view # to self and we'll refresh them together. self.model.jobdesc_textfield.view = self self.model.progressdesc_textfield.view = self self.setModal(True) self.setAutoReset(False) self.setAutoClose(False) self._timer = QTimer(self) self._timer.timeout.connect(self.model.pulse)
def __init__(self, iface, db, unassigned, export_path): self.killed = False self.iface = iface self.db = db self.unassigned = unassigned self.export_path = export_path self.prepare_sql_queries() self.progresswin = QProgressDialog("Exporting Shapefile...", "Abort", 0, 100) self.progresswin.setWindowModality(Qt.WindowModal) self.progresswin.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint) self.progresswin.setWindowTitle(" ")
def __init__(self, theParent=None, theIface=None): """Constructor for import dialog. Args: * theParent - Optional widget to use as parent * theIface - an instance of QGisInterface Returns: not applicable Raises: no exceptions explicitly raised """ QDialog.__init__(self, theParent) self.parent = theParent self.setupUi(self) self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader')) self.iface = theIface self.url = "http://osm.linfiniti.com/buildings-shp" ## region coordinate: (latitude, longtitude, zoom_level) self.regionExtent = { '0': [18.87685, -71.493, 6], # haiti '1': [-2.5436300, 116.8887, 3], # indonesia '2': [1.22449, 15.40999, 2], # africa '3': [34.05, 56.55, 3], # middle east '4': [12.98855, 121.7166, 4], # philipine } # creating progress dialog for download self.progressDialog = QProgressDialog(self) self.progressDialog.setAutoClose(False) myTitle = self.tr("InaSAFE OpenStreetMap Downloader") self.progressDialog.setWindowTitle(myTitle) ## set map parameter based on placeholder self.map widget theMap = InasafeLightMaps(self.gbxMap) theMap.setGeometry(self.map.geometry()) theMap.setSizePolicy(self.map.sizePolicy()) self.map = theMap self.nam = QNetworkAccessManager(self) self.setupOptions() self.restoreState() self.cbxRegion.currentIndexChanged.connect(self.regionChanged) self.map.m_normalMap.updated.connect(self.updateExtent)
class BlockingTask(QObject): """ Blocking task provides a UI wrapper for long running tasks. While the task is executed a modal progress dialog will be shown. The task can be canceled through the UI. """ load_finished = pyqtSignal(scene.Scene) def __init__(self, scene_load_func, message, *args, **kwargs): super(BlockingTask, self).__init__(*args, **kwargs) self.scene_load_func = scene_load_func self.message = message self.progress_bar = QProgressBar() self.progress_bar.setRange(0, 0) self.worker = None def start_task(self): self._async_execute() def _on_load_finished(self): logger.debug('On task finished') self.scene = self.worker.result if self.scene is not None: self.load_finished.emit(self.scene) self.progress_dialog.hide() def _on_load_start(self): logger.debug('On task start') self.progress_dialog = QProgressDialog(self.message, "Abort", 0, 0, self.parent(), flags=Qt.CustomizeWindowHint, ) self.progress_dialog.setWindowModality(Qt.WindowModal) self.progress_dialog.canceled.connect(self._abort) self.progress_dialog.show() def _abort(self): self.worker.terminate() def _async_execute(self): self._on_load_start() self.worker = TaskWorker(self.scene_load_func) self.worker.task_done.connect(self._on_load_finished) self.worker.start()
def __init__(self, iface, db, validation_dia, plugin_dir, params): self.iface = iface self.db = db self.params = params self.validation_dia = validation_dia self.app_root = plugin_dir self.open_image = QPixmap(os.path.join(self.app_root, "image", "folder_open_icon.png")) self.validation_dia.ui.openPushButton.setIcon(QIcon(self.open_image)) self.validation_dia.ui.openPushButton.setToolTip("Select File") self.export_globals = None self.validation_dk = None self.report_to_dialog = None self.re = QRegExp("CheckBox") self.check_boxes_names = [] self.long_task = QThreadPool(None).globalInstance() self.summary_tables = {} self.model_navigation() self.form_load() self.file_dialog = QFileDialog() self.summary_functions = {} self.report_file_path = None self.home_dir = os.path.expanduser('~') self.org_name = database.get_from_gaz_metadata(db, "owner") self.report = ExportValidationReport("roadNet Validation Report", self.org_name, self.db, self.iface, None) self.list_check_boxes = [] self.progress_win = QProgressDialog("", None, 0, 100, self.validation_dia) self.progress_win.setFixedSize(380, 100) self.progress_win.setModal(True) self.progress_win.setWindowTitle("Export Validation Report") self.summary_runnables = {'dupStreetCheckBox': [lambda: DupStreetDesc(), 0], 'notStreetEsuCheckBox': [lambda: StreetsNoEsuDesc(), 1], 'notType3CheckBox': [lambda: Type3Desc(False), 2], 'incFootPathCheckBox': [lambda: Type3Desc(True), 2], 'dupEsuRefCheckBox': [lambda: DupEsuRef(True), 3], 'notEsuStreetCheckBox': [lambda: NoLinkEsuStreets(), 4], 'invCrossRefCheckBox': [lambda: InvalidCrossReferences()], 'startEndCheckBox': [lambda: CheckStartEnd(), 8], 'tinyEsuCheckBox': [lambda: CheckTinyEsus("esu", 1)], 'notMaintReinsCheckBox': [lambda: CheckMaintReins()], 'asdStartEndCheckBox': [lambda: CheckAsdCoords()], 'notMaintPolysCheckBox': [lambda: MaintNoPoly(), 16], 'notPolysMaintCheckBox': [lambda: PolyNoMaint()], 'tinyPolysCheckBox': [lambda: CheckTinyEsus("rd_poly", 1)]}
def __init__(self, parent=None, **kwargs): super().__init__(parent, acceptDrops=True, **kwargs) self.setLayout(QVBoxLayout()) self.layout().setContentsMargins(0, 0, 0, 0) self.addonwidget = AddonManagerWidget() self.layout().addWidget(self.addonwidget) info_bar = QWidget() info_layout = QHBoxLayout() info_bar.setLayout(info_layout) self.layout().addWidget(info_bar) buttons = QDialogButtonBox( orientation=Qt.Horizontal, standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttons.accepted.connect(self.__accepted) buttons.rejected.connect(self.reject) self.layout().addWidget(buttons) # No system access => install into user site-packages self.user_install = not os.access(sysconfig.get_path("purelib"), os.W_OK) self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) if AddonManagerDialog._packages is None: self._f_pypi_addons = self._executor.submit(list_pypi_addons) else: self._f_pypi_addons = concurrent.futures.Future() self._f_pypi_addons.set_result(AddonManagerDialog._packages) self._f_pypi_addons.add_done_callback( method_queued(self._set_packages, (object,)) ) self.__progress = QProgressDialog( self, Qt.Sheet, minimum=0, maximum=0, labelText=self.tr("Retrieving package list"), sizeGripEnabled=False, windowTitle="Progress" ) self.__progress.rejected.connect(self.reject) self.__thread = None self.__installer = None
def run(self): if self._configuration: try: self._configuration.check_all() self._reinit_simu() self._progress_bar = QProgressDialog("Simulating...", "Abort", 0, 100) self._progress_bar.canceled.connect(self.abort) self._progress_bar.show() self.worker = RunSimulation() self._model = Model(self._configuration, callback=self.worker.updateProgressBar) self.worker.set_model(self._model) self.worker.finished.connect(self.runFinished) self.worker.start() QObject.connect(self.worker, SIGNAL("updateProgressBar"), self.updateProgressBar) except Exception as msg: QMessageBox.warning(self, "Configuration error", str(msg)) self._reinit_simu() self.runFinished()
def __init__(self,url,dirpath=None,parent=None): super(QDialog,self).__init__(parent) if dirpath is not None and not os.path.exists(dirpath):os.mkdir(dirpath) self.url=url self.progress_dialog=QProgressDialog() self.progress_dialog.setWindowTitle(u"登录中") self.progress_dialog.setLabelText(u"登录中") self.loading_dialog=QDialog(self) self.dirpath=dirpath self.list=QListWidget() self.layout=QHBoxLayout(self) self.button_layout=QVBoxLayout() self.layout.addWidget(self.list) self.layout.addLayout(self.button_layout) self.add_button=QPushButton(u"添加") self.edit_name_button=QPushButton(u"设置名字") self.edit_cookies_button=QPushButton(u"设置Cookies") self.delete_button=QPushButton(u"删除") self.refresh_button=QPushButton(u"刷新") self.button_layout.addWidget(self.add_button) self.button_layout.addWidget(self.delete_button) self.button_layout.addWidget(self.refresh_button) self.button_layout.addWidget(self.edit_name_button) self.button_layout.addWidget(self.edit_cookies_button) QObject.connect(self.add_button,SIGNAL("clicked()"),self._add) QObject.connect(self.edit_name_button,SIGNAL("clicked()"),self.edit_name) QObject.connect(self.edit_cookies_button,SIGNAL("clicked()"),self.edit_cookies) QObject.connect(self.delete_button,SIGNAL("clicked()"),self._delete) QObject.connect(self.refresh_button,SIGNAL("clicked()"),self.login)
def sizeHint(self): size = QProgressDialog.sizeHint(self) if size.width() < 400: size.setWidth(400) return size
def _show_backup_decision(self, error=None): text = '<p>{0}</p><p>{1}</p>'.format( self.BACKUP_INTRO_TEXT if error is None else error, self.BACKUP_PROMPT_TEXT, ) dialog = QMessageBox( QMessageBox.Question if error is None else QMessageBox.Critical, self.BACKUP_DIALOG_CAPTION if error is None else self.BACKUP_DIALOG_ERROR_CAPTION, text, ) revert_button = dialog.addButton(self.REVERT_BACKUP_BUTTON_TEXT, QMessageBox.AcceptRole) delete_button = dialog.addButton(self.DELETE_BACKUP_BUTTON_TEXT, QMessageBox.DestructiveRole) examine_button = dialog.addButton(self.EXAMINE_BACKUP_BUTTON_TEXT, QMessageBox.ActionRole) dialog.addButton(self.QUIT_BUTTON_TEXT, QMessageBox.RejectRole) dialog.exec() clicked_button = dialog.clickedButton() if clicked_button == examine_button: QMetaObject.invokeMethod(self, '_examine_backup', Qt.QueuedConnection) elif clicked_button == revert_button: self._progress_dialog = QProgressDialog(None) self._progress_dialog.setLabelText(self.REVERT_BACKUP_PROGRESS_TEXT) self._progress_dialog.setCancelButton(None) self._progress_dialog.setRange(0, 0) self._progress_dialog.forceShow() self.request_revert_backup.emit() elif clicked_button == delete_button: self.request_delete_backup.emit() else: self.quit()
def preRun(self, name): if not hasattr(self, 'dlg'): self.dlg = QProgressDialog(Globals.mainWin) self.dlg.setWindowTitle(QCoreApplication.translate('Executor', 'Execution progress')) self.dlg.connect(self.dlg, SIGNAL("canceled()"), self.cancel) self.dlg.show() self.dlg.setValue(0)
def __init__(self, parent=None, iface=None): """Constructor for import dialog. :param parent: Optional widget to use as parent :type parent: QWidget :param iface: An instance of QGisInterface :type iface: QGisInterface """ QDialog.__init__(self, parent) self.parent = parent self.setupUi(self) self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader')) self.iface = iface self.url = "http://osm.linfiniti.com/buildings-shp" # creating progress dialog for download self.progressDialog = QProgressDialog(self) self.progressDialog.setAutoClose(False) myTitle = self.tr("InaSAFE OpenStreetMap Downloader") self.progressDialog.setWindowTitle(myTitle) # Set up context help helpButton = self.buttonBox.button(QtGui.QDialogButtonBox.Help) QtCore.QObject.connect(helpButton, QtCore.SIGNAL('clicked()'), self.show_help) self.show_info() self.network_manager = QNetworkAccessManager(self) self.restore_state() self.update_extent()
def downloadNewMessages(self, messageType): """ Starts a thread that downloads all the new messages for the user’s accounts """ newMessageCount = self.gatherData.countNewMessages(messageType) noun = newMessageCount == 1 and "message" or "messages" self.progress = QProgressDialog(str(newMessageCount) + " " + noun + " to download.", "Cancel", 0, 10) self.progress.resize(400, 50) self.progress.setMaximum(newMessageCount) self.progress.show() thread = Thread(target=self.fetchMessagesThread, name="Fetch messages", args=(messageType,)) self.connect(self, SIGNAL("updateProgressBar(PyQt_PyObject)"), self.updateProgressBar) self.connect(self, SIGNAL("refreshLists()"), self.refreshLists) self.connect(self.progress, SIGNAL("canceled()"), self.cancelMessageRetrieval) self.connect( self, SIGNAL("askUserAQuestion(PyQt_PyObject, PyQt_PyObject, PyQt_PyObject, PyQt_PyObject, PyQt_PyObject)"), self.askUserAQuestion, ) thread.start()
def __init__(self, parent=None, **kwargs): super(AddonManagerDialog, self).__init__(parent, **kwargs) self.setLayout(QVBoxLayout()) self.addonwidget = AddonManagerWidget() self.addonwidget.layout().setContentsMargins(0, 0, 0, 0) self.layout().addWidget(self.addonwidget) buttons = QDialogButtonBox( orientation=Qt.Horizontal, standardButtons=QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttons.accepted.connect(self.__accepted) buttons.rejected.connect(self.reject) self.layout().addWidget(buttons) self.__progress = QProgressDialog( self, Qt.Sheet, minimum=0, maximum=0, labelText=self.tr("Retrieving package list"), sizeGripEnabled=False, windowTitle="Progress" ) self.__progress.canceled.connect(self.reject) # The installer thread self.__thread = None # The installer object self.__installer = None
def __init__(self, iface, public_only, unassigned, export_path, db): QtCore.QObject.__init__(self) self.killed = False self.iface = iface self.db = db self.unassigned = unassigned self.public_only = public_only self.export_path = export_path self.prepare_sql_queries() self.percent_complete = None self.progresswin = QProgressDialog("Exporting Shapefile...", "Abort", 0, 100) self.progresswin.setWindowModality(Qt.WindowModal) self.progresswin.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint) self.progresswin.setWindowModality(Qt.WindowModal)
def __init__(self, parent=None, iface=None): """Constructor for import dialog. .. versionadded: 3.3 :param parent: Optional widget to use as parent. :type parent: QWidget :param iface: An instance of QGisInterface. :type iface: QGisInterface """ QDialog.__init__(self, parent) self.parent = parent self.setupUi(self) title = self.tr('PetaBencana Downloader') self.setWindowTitle(title) self.iface = iface self.source = None self.radio_button_group = QButtonGroup() self.radio_button_group.addButton(self.radio_button_production) self.radio_button_group.addButton(self.radio_button_development) self.radio_button_group.setExclusive(True) self.radio_button_production.setChecked(True) self.populate_combo_box() developer_mode = setting('developer_mode', False, bool) if not developer_mode: self.radio_button_widget.hide() self.source_label.hide() self.output_group.adjustSize() # signals self.radio_button_production.clicked.connect(self.populate_combo_box) self.radio_button_development.clicked.connect(self.populate_combo_box) # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) self.progress_dialog.setWindowTitle(title) # Set up things for context help self.help_button = self.button_box.button(QtGui.QDialogButtonBox.Help) # Allow toggling the help button self.help_button.setCheckable(True) self.help_button.toggled.connect(self.help_toggled) self.main_stacked_widget.setCurrentIndex(1) # set up the validator for the file name prefix expression = QRegExp('^[A-Za-z0-9-_]*$') validator = QRegExpValidator(expression, self.filename_prefix) self.filename_prefix.setValidator(validator) self.time_stamp = None self.restore_state()
def __init__(self, parent=None, iface=None): """Constructor for import dialog. :param parent: Optional widget to use as parent :type parent: QWidget :param iface: An instance of QGisInterface :type iface: QGisInterface """ QDialog.__init__(self, parent) self.parent = parent self.setupUi(self) self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader')) self.iface = iface self.buildings_url = 'http://osm.linfiniti.com/buildings-shp' self.building_points_url = \ 'http://osm.linfiniti.com/building-points-shp' self.roads_url = 'http://osm.linfiniti.com/roads-shp' self.help_context = 'openstreetmap_downloader' # creating progress dialog for download self.progress_dialog = QProgressDialog(self) self.progress_dialog.setAutoClose(False) title = self.tr('InaSAFE OpenStreetMap Downloader') self.progress_dialog.setWindowTitle(title) # Set up context help help_button = self.button_box.button(QtGui.QDialogButtonBox.Help) help_button.clicked.connect(self.show_help) self.show_info() # set up the validator for the file name prefix expression = QRegExp('^[A-Za-z0-9-_]*$') validator = QRegExpValidator(expression, self.filename_prefix) self.filename_prefix.setValidator(validator) # Set Proxy in webpage proxy = get_proxy() self.network_manager = QNetworkAccessManager(self) if proxy is not None: self.network_manager.setProxy(proxy) self.restore_state() # Setup the rectangle map tool self.canvas = iface.mapCanvas() self.rectangle_map_tool = \ RectangleMapTool(self.canvas) self.rectangle_map_tool.rectangle_created.connect( self.update_extent_from_rectangle) self.button_extent_rectangle.clicked.connect( self.drag_rectangle_on_map_canvas) # Setup pan tool self.pan_tool = QgsMapToolPan(self.canvas) self.canvas.setMapTool(self.pan_tool) self.update_extent_from_map_canvas()
def createPortfolioListModel(self): portfolios = self.getPortfolios() listModel = PortfolioListModel(portfolios) numPortfolios = len(portfolios) progress = QProgressDialog( self.tr("Loading portfolios from Google"), QString(), 0, numPortfolios, self.mainWindow ) progress.setWindowTitle(self.tr("Loading portfolios from Google")) if self.updater: self.updater.terminate() self.disconnect(self.updater, SIGNAL("quotesUpdated"), self.processQuotesUpdated) self.updater = Updater(self.quoter) QObject.connect(self.updater, SIGNAL("quotesUpdated"), self.processQuotesUpdated) for pIndex in range(numPortfolios): portfolio = portfolios[pIndex] positions = self.gDataClient.GetPositionFeed(portfolio) for position in positions.entry: tickerTuple = position.symbol.exchange, position.symbol.symbol self.updater.addTickers(tickerTuple) portfolioName = portfolio.title.text.decode("utf-8") labelText = QString("'%s' (%d / %d)" % (portfolioName, pIndex + 1, numPortfolios)) progress.setLabelText(labelText) progress.setValue(pIndex + 1) QApplication.processEvents() self.updater.start() return listModel
def redo(self): keys = self.receiver.sourceList.elements.keys() progress = QProgressDialog("Storing DataSource elements", QString(), 0, len(keys), self.receiver.sourceList) progress.setWindowTitle("Store All DataSources") progress.setWindowModality(Qt.WindowModal) progress.show() for i in range(len(keys)): ids = keys[i] ds = self.receiver.sourceList.elements[ids] if ds.instance is None: dsEdit = DataSource.DataSource(self.receiver.sourceList) dsEdit.id = ds.id dsEdit.directory = self.receiver.sourceList.directory dsEdit.name = \ self.receiver.sourceList.elements[ds.id].name ds.instance = dsEdit logger.debug("Store %s" % ds.instance.name) try: xml = ds.instance.get() if not self.receiver.configServer.connected: QMessageBox.information( self.receiver, "Connecting to Configuration Server", "Connecting to %s on %s:%s" % (self.receiver.configServer.device, self.receiver.configServer.host, self.receiver.configServer.port)) self.receiver.configServer.connect() self.receiver.disableServer(False) if ds.instance.name: self.receiver.configServer.storeDataSource( ds.instance.dataSourceName, xml) else: self.receiver.configServer.storeDataSource( ds.instance.name, xml) ds.instance.savedXML = xml ds.savedName = ds.name except Exception, e: QMessageBox.warning(self.receiver, "Error in datasource storing", unicode(e)) progress.setValue(i)
def redo(self): keys = self.receiver.componentList.elements.keys() progress = QProgressDialog("Storing Component elements", QString(), 0, len(keys), self.receiver.componentList) progress.setWindowTitle("Store All Components") progress.setWindowModality(Qt.WindowModal) progress.show() for i in range(len(keys)): icp = keys[i] cp = self.receiver.componentList.elements[icp] if cp.instance is None: # self._cpEdit = FieldWg() cpEdit = Component(self.receiver.componentList) cpEdit.id = cp.id cpEdit.directory = self.receiver.componentList.directory cpEdit.name = self.receiver.componentList.elements[cp.id].name cpEdit.createGUI() cpEdit.addContextMenu(self.receiver.contextMenuActions) cpEdit.createHeader() cpEdit.dialog.setWindowTitle("%s [Component]" % cp.name) cp.instance = cpEdit try: cp.instance.merge(False) xml = cp.instance.get() if not self.receiver.configServer.connected: QMessageBox.information( self.receiver, "Connecting to Configuration Server", "Connecting to %s on %s:%s" % (self.receiver.configServer.device, self.receiver.configServer.host, self.receiver.configServer.port)) self.receiver.configServer.connect() self.receiver.disableServer(False) self.receiver.configServer.storeComponent( cp.instance.name, xml) cp.instance.savedXML = xml cp.savedName = cp.name except Exception, e: QMessageBox.warning(self.receiver, "Error in storing the component", unicode(e)) progress.setValue(i)
def start(self): """ To start the rebuild """ snap_util = self.__iface.mapCanvas().snappingUtils() extent = self.__iface.mapCanvas().extent() self.__progressDialog = QProgressDialog() self.__progressDialog.setWindowTitle( QCoreApplication.translate("VDLTools", "Rebuild Index...")) self.__progressDialog.setLabelText( QCoreApplication.translate("VDLTools", "Percentage of indexed layers")) progressBar = QProgressBar(self.__progressDialog) progressBar.setTextVisible(True) cancelButton = QPushButton() cancelButton.setText(QCoreApplication.translate("VDLTools", "Cancel")) cancelButton.clicked.connect(self.kill) self.__progressDialog.setBar(progressBar) self.__progressDialog.setCancelButton(cancelButton) self.__progressDialog.setMinimumWidth(300) self.__progressDialog.show() lcs_list = snap_util.layers() step = 0 self.killed = False for lc in lcs_list: if self.killed: break locator = snap_util.locatorForLayer(lc.layer) if locator.extent() is not None: txt = locator.extent().toString() else: txt = "None" print("old extent : " + txt) print("new extent : " + extent.toString()) locator.setExtent(extent) if not locator.hasIndex(): locator.init() else: locator.rebuildIndex() locator.setExtent(None) progressBar.setValue(100 * step / len(lcs_list)) step += 1 self.__progressDialog.close()
def init_from_pgn(self, mainWindow, msg): print("loading from: "+self.filename) with open(self.filename) as pgn: size = os.path.getsize(self.filename) self.entries = [] pDialog = QProgressDialog(msg,None,0,size,mainWindow) pDialog.show() pDialog.setWindowModality(PyQt4.QtCore.Qt.WindowModal) QApplication.processEvents() for offset, headers in chess.pgn.scan_headers(pgn): print(headers) QApplication.processEvents() pDialog.setValue(offset) self.entries.append(Entry(offset,headers)) pDialog.close() self.checksum = crc32_from_file(self.filename)
def transferPoints(self, other): params = parameters.instance current_data = self.current_data items = self.selectedItems() if len(items) == 0: items = [it for it in self.points.values() if it.arrow is None and it.link is None] new_pt_ids = [] new_pt_pos = [] move_pt_ids = [] move_pt_new_pos = [] if params.estimate: progress = QProgressDialog("Estimating position of the points...", "Abort", 0, len(items), self.parent()) progress.setMinimumDuration(1) size = (params.filter_size, params.filter_size) im1 = image_cache.cache.numpy_array(self.image_path, size) im2 = image_cache.cache.numpy_array(other.image_path, size) for i, it in enumerate(items): pos = self.findPoint(im1, im2, other, it) id = it.pt_id if id in other.points: move_pt_ids.append(id) move_pt_new_pos.append(pos) else: new_pt_ids.append(id) new_pt_pos.append(pos) progress.setValue(i+1) if progress.wasCanceled(): progress.hide() break else: for it in items: id = it.pt_id pos = current_data[id] if id in other.points: move_pt_ids.append(id) move_pt_new_pos.append(pos) else: new_pt_ids.append(id) new_pt_pos.append(pos) if new_pt_ids or move_pt_ids: self.undo_stack.beginMacro("Transfer point(s) from %s to %s" % (self.image_name, other.image_name)) if new_pt_ids: other.planAddPoints(new_pt_ids, new_pt_pos) if move_pt_ids: other.planMovePoints(move_pt_ids, move_pt_new_pos) self.undo_stack.endMacro()
def run(self): """Run a thread""" i = 0 progressDialog = QProgressDialog(QString(), QString(), 0, 100) #progressDialog.setLabelText(self.__message) #progressDialog.setWindowTitle("Wait...") #progressDialog.setRange(0, 10000) #print 'Max',progressDialog.maximum() sleepingTime = 0 #gLogger.info('Thread run') while (not self.__stoped): i = i + 1 if i == progressDialog.maximum(): sleepingTime = 1 i = 0 #progressDialog.setLabelText(self.tr(self.__message)) progressDialog.setValue(i) #QCoreApplication.processEvents() #qApp.processEvents() time.sleep(sleepingTime) self.__stoped = False
def process(self): dirs = sorted(glob.glob(self.rootDir + '\\*_mask*')) total2Proc = 100 progress = QProgressDialog("Tracking leaves...", "Abort", 0, total2Proc, self) progress.setWindowTitle("Batch Process") progress.setWindowModality(QtCore.Qt.WindowModal) try: self.particleTracker(dirs, progressBar=progress) progress.setValue(total2Proc) qm = QtGui.QMessageBox qm.information(self, 'Completed', 'Leaf labels were changed.') except Exception as e: progress.cancel() qm = QtGui.QMessageBox qm.information(self, 'Error', '{}'.format(e)) raise e
def _on_load_start(self): logger.debug('On task start') self.progress_dialog = QProgressDialog(self.message, "Abort", 0, 0, self.parent(), flags=Qt.CustomizeWindowHint, ) self.progress_dialog.setWindowModality(Qt.WindowModal) self.progress_dialog.canceled.connect(self._abort) self.progress_dialog.show()
def on_action_2_triggered(self): """ Slot documentation goes here. """ # TODO: not implemented yet if self.model.rowCount < 1: QtGui.QMessageBox.warning(self,'warning', "Nothing could be export") return fileName = QFileDialog.getSaveFileName(self,self.tr('Save csv'),'',self.tr("*.csv")) if platform.system() == 'Windows': fileName = str(fileName.toUtf8()).encode('gbk') content = '' for j in range(self.model.columnCount()): content += str(self.model.headerData(j, QtCore.Qt.Horizontal).toString().toUtf8())+ ',' for j in range(self.model.columnCount()): content += str(self.model2.headerData(j, QtCore.Qt.Horizontal).toString().toUtf8())+ ',' content = content[:-1] + '\r\n' progressDialog = QProgressDialog(u"正在导出 (%d/%d)" %(0, self.model.rowCount()), u"取消", 0, self.model.rowCount(), self) for i in range(self.model.rowCount()): for j in range(self.model.columnCount()): content += str(self.model.data(self.model.index(i, j)).toString().toUtf8())+ ',' for j in range(self.model2.columnCount()): content += str(self.model2.data(self.model2.index(i, j)).toString().toUtf8())+ ',' content = content[:-1] + '\r\n' if progressDialog.wasCanceled(): return progressDialog.setLabelText (u"正在导出 (%d/%d)" %(i+1, self.model.rowCount())) progressDialog.setValue(i+1) if platform.system() == 'Windows': content = content.decode('utf-8').encode('gbk') f = open(fileName, 'wb') f.write(content) f.close()
def link_clicked(self, url): surl = str(url.toString()) if surl.endswith('.epub'): progress = QProgressDialog("Downloding the book...", "Abort", 0, -1, self) progress.show() book_id = FeedBooks().download(surl[:-5]) progress.close() if not book_id: QMessageBox.critical(self, 'Error', 'Could not download the ' 'book') elif book_id != -1: book = Book(book_id) insert_library(book) self.parent().library.refresh() else: book_id = surl[surl.rfind('/')+1:-5] if book_id: self.load_book(book_id) else: webbrowser.open_new_tab(surl)