Example #1
0
 def _clientLoginCallback(self, realm, username, may_save):
     """
     Protected method called by the client to get login information.
     
     @param realm name of the realm of the requested credentials (string)
     @param username username as supplied by subversion (string)
     @param may_save flag indicating, that subversion is willing to save
         the answers returned (boolean)
     @return tuple of four values (retcode, username, password, save).
         Retcode should be True, if username and password should be used
         by subversion, username and password contain the relevant data
         as strings and save is a flag indicating, that username and
         password should be saved.
     """
     from .SvnLoginDialog import SvnLoginDialog
     cursor = QApplication.overrideCursor()
     if cursor is not None:
         QApplication.restoreOverrideCursor()
     parent = isinstance(self, QWidget) and self or None
     dlg = SvnLoginDialog(realm, username, may_save, parent)
     res = dlg.exec_()
     if cursor is not None:
         QApplication.setOverrideCursor(Qt.WaitCursor)
     if res == QDialog.Accepted:
         loginData = dlg.getData()
         return (True, loginData[0], loginData[1], loginData[2])
     else:
         return (False, "", "", False)
Example #2
0
    def install_kgsbrf(self):
        """Download and install the kgs_brf software."""
        if os.name != 'nt':
            url_t = "https://github.com/jnsebgosselin/gwhat/issues"
            msg = ("This feature is currently not supported for your"
                   " operating system. Please open a ticket in our"
                   " <a href=\"%s\">Issues Tracker</a>.") % url_t
            QMessageBox.warning(self, 'Warning', msg, QMessageBox.Ok)
            return

        print("Installing KGS_BRF software...", end=" ")
        QApplication.setOverrideCursor(Qt.WaitCursor)
        url = "http://www.kgs.ku.edu/HighPlains/OHP/index_program/KGS_BRF.zip"
        request = requests.get(url)
        zfile = zipfile.ZipFile(io.BytesIO(request .content))

        if not os.path.exists(self.install_dir):
            os.makedirs(self.install_dir)

        with open(self.kgs_brf_path, 'wb') as f:
            f.write(zfile.read(self.kgs_brf_name))

        if self.kgsbrf_is_installed():
            self.sig_kgs_brf_installed.emit(self.install_dir)
            self.close()
            print("done")
        else:
            print("failed")
        QApplication.restoreOverrideCursor()
Example #3
0
 def __finish(self):
     """
     Private slot called when the process finished or the user pressed
     the button.
     """
     QApplication.restoreOverrideCursor()
     
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
     self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
     
     self.refreshButton.setEnabled(True)
     self.__updateButtons()
     self.__updateCommitButton()
     
     self.__statusFilters.sort()
     self.__statusFilters.insert(0, "<{0}>".format(self.tr("all")))
     self.statusFilterCombo.addItems(self.__statusFilters)
     
     for act in self.menuactions:
         act.setEnabled(True)
     
     self.__resizeColumns()
     self.__resort()
     
     self._cancel()
Example #4
0
 def __finish(self):
     """
     Private slot called when the user pressed the button.
     """
     QApplication.restoreOverrideCursor()
     
     self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
     self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
     
     tc = self.contents.textCursor()
     tc.movePosition(QTextCursor.Start)
     self.contents.setTextCursor(tc)
     self.contents.ensureCursorVisible()
     
     self.filesCombo.addItem(self.tr("<Start>"), 0)
     self.filesCombo.addItem(self.tr("<End>"), -1)
     for oldFile, newFile, pos in sorted(self.__fileSeparators):
         if oldFile != newFile:
             self.filesCombo.addItem(
                 "{0}\n{1}".format(oldFile, newFile), pos)
         else:
             self.filesCombo.addItem(oldFile, pos)
     
     self._cancel()
Example #5
0
 def __updateChildren(self, sstyle):
     """
     Private slot to change the style of the show UI.
     
     @param sstyle name of the selected style (string)
     """
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     qstyle = QStyleFactory.create(sstyle)
     self.mainWidget.setStyle(qstyle)
     
     lst = self.mainWidget.findChildren(QWidget)
     for obj in lst:
         try:
             obj.setStyle(qstyle)
         except AttributeError:
             pass
     del lst
     
     self.mainWidget.hide()
     self.mainWidget.show()
     
     self.lastQStyle = qstyle
     self.lastStyle = sstyle
     Preferences.Prefs.settings.setValue(
         'UIPreviewer/style', self.styleCombo.currentIndex())
     QApplication.restoreOverrideCursor()
Example #6
0
File: ocsvm.py Project: rhoef/afw
    def checkParameters(self, parent):
        """Pop up a dialog and ask the user wether to proceed with current
        unoptimized parameters, run cross validation or cancel.
        """

        title = "Optimize Parameters"
        text = "You need to optimize SVM parameters before you predict."

        QApplication.restoreOverrideCursor()

        qmb = QMessageBox(QMessageBox.Question, title, text, parent=parent)
        ignoreBtn = qmb.addButton(qmb.Ignore)
        cancelBtn = qmb.addButton(qmb.Cancel)
        runBtn = qmb.addButton(
            "Optimize", qmb.AcceptRole)
        qmb.exec_()

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        if qmb.clickedButton() == runBtn:
            # parent sets some flag
            parent.estimateParameters()
            return True
        elif qmb.clickedButton() == ignoreBtn:
            return True
        elif qmb.clickedButton() == cancelBtn:
            return False

        raise RuntimeError()
Example #7
0
 def loadBinary(self, filename):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     if self.treeView.manifest.compression == 'gzip':
         reader = gzip.open
     elif self.treeView.manifest.compression == 'bz2':
         reader = bz2.BZ2File
     else:
         reader = open
     try:
         with reader(filename, 'rb') as f:
             data = f.read()
         self.qHexEdit.setData(data)
         self._current_filename = filename
         self.statusBar.showMessage(
             self.tr("Loaded binary: ") + os.path.basename(filename),
             STATUSBAR_TIMEOUT
         )
         self.refreshTitle()
     except IOError as e:
         QErrorMessage(self).showMessage(
             self.tr('Format Error: ') + str(e)
         )
         logger.exception(e)
     finally:
         self.treeView.refresh_view()
         QApplication.restoreOverrideCursor()
Example #8
0
 async def accept(self):
     """
     Validate the dialog
     """
     pubkey = self.selected_pubkey()
     if pubkey:
         password = await self.password_asker.async_exec()
         if password == "":
             self.ui.button_box.setEnabled(True)
             return
         QApplication.setOverrideCursor(Qt.WaitCursor)
         result = await self.account.certify(password, self.community, pubkey)
         if result[0]:
             if self.app.preferences['notifications']:
                 toast.display(self.tr("Certification"),
                               self.tr("Success sending certification"))
             else:
                 await QAsyncMessageBox.information(self.widget, self.tr("Certification"),
                                              self.tr("Success sending certification"))
             QApplication.restoreOverrideCursor()
             self.widget.accept()
         else:
             if self.app.preferences['notifications']:
                 toast.display(self.tr("Certification"), self.tr("Could not broadcast certification : {0}"
                                                                 .format(result[1])))
             else:
                 await QAsyncMessageBox.critical(self.widget, self.tr("Certification"),
                                           self.tr("Could not broadcast certification : {0}"
                                                                 .format(result[1])))
             QApplication.restoreOverrideCursor()
             self.ui.button_box.setEnabled(True)
Example #9
0
    def accept(self):
        self.button_box.setEnabled(False)
        if self.radio_contact.isChecked():
            for contact in self.account.contacts:
                if contact['name'] == self.combo_contact.currentText():
                    pubkey = contact['pubkey']
                    break
        else:
            pubkey = self.edit_pubkey.text()

        password = yield from self.password_asker.async_exec()
        if password == "":
            self.button_box.setEnabled(True)
            return
        QApplication.setOverrideCursor(Qt.WaitCursor)
        result = yield from self.account.certify(password, self.community, pubkey)
        if result[0]:
            if self.app.preferences['notifications']:
                toast.display(self.tr("Certification"),
                              self.tr("Success sending certification"))
            else:
                yield from QAsyncMessageBox.information(self, self.tr("Certification"),
                                             self.tr("Success sending certification"))
            QApplication.restoreOverrideCursor()
            super().accept()
        else:
            if self.app.preferences['notifications']:
                toast.display(self.tr("Certification"), self.tr("Could not broadcast certification : {0}"
                                                                .format(result[1])))
            else:
                yield from QAsyncMessageBox.critical(self, self.tr("Certification"),
                                          self.tr("Could not broadcast certification : {0}"
                                                                .format(result[1])))
            QApplication.restoreOverrideCursor()
            self.button_box.setEnabled(True)
Example #10
0
 def _completeRepopulateItem(self, name):
     """
     Protected slot to handle the completeRepopulateItem signal.
     
     @param name relative name of file item to be repopulated (string)
     """
     sindex = self._model.itemIndexByName(name)
     if sindex.isValid():
         index = self.model().mapFromSource(sindex)
         if index.isValid():
             if self.isExpanded(index):
                 childIndex = self.indexBelow(index)
                 while childIndex.isValid():
                     if not childIndex.isValid() or \
                             childIndex.parent() == index.parent():
                         break
                     itm = self.model().item(childIndex)
                     if itm is not None:
                         itemData = itm.data(0)
                         if self.currentItemName and \
                                 self.currentItemName == itemData:
                             self._selectSingleItem(childIndex)
                         if itemData in self.expandedNames:
                             self.setExpanded(childIndex, True)
                     childIndex = self.indexBelow(childIndex)
             else:
                 self._selectSingleItem(index)
             self.expandedNames = []
     self.currentItemName = None
     QApplication.restoreOverrideCursor()
     QApplication.processEvents()
     self._resort()
    def adjust_mouse_cursor(self, event):
        """

        """

        if self.getInnerRect().contains(event.pos()):
            QApplication.restoreOverrideCursor()
            QApplication.setOverrideCursor(Qt.SizeAllCursor)
        else:
            cursor = Qt.SizeAllCursor

            if self.resizeDirection.horizontal != ResizeDirectionHorizontal.HorzNone:
                cursor = Qt.SizeHorCursor

            if self.resizeDirection.vertical != ResizeDirectionVertical.VertNone:
                cursor = Qt.SizeVerCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Top and
                    self.resizeDirection.horizontal == ResizeDirectionHorizontal.Left):
                cursor = Qt.SizeFDiagCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Bottom and
                    self.resizeDirection.horizontal == ResizeDirectionHorizontal.Right):
                cursor = Qt.SizeFDiagCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Top and
                    self.resizeDirection.horizontal == ResizeDirectionHorizontal.Right):
                cursor = Qt.SizeBDiagCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Bottom and
                    self.resizeDirection.horizontal == ResizeDirectionHorizontal.Left):
                cursor = Qt.SizeBDiagCursor

            self.__set_mouse_cursor(cursor)
Example #12
0
 def loadFile(self, fileName):
     """
     Open an existing project file
     """
     file = QFile(fileName)
     if not file.open(QFile.ReadOnly | QFile.Text):
         flag = True
     QApplication.setOverrideCursor(Qt.WaitCursor)
     # read a project and create scenario
     if self.project.read(fileName):
         #self.outputs_refresh()
         self.table_list_refresh('scenario')
         self.table_list_refresh('event')
         self.project_display()
         self.protocol_display()
         QApplication.restoreOverrideCursor()
         self.setCurrentFile(fileName)
         flag = False
     else:
         flag = True
     if flag:
         QMessageBox.warning(self, "Lekture Error 123",
                             "Cannot read file %s:\n%s." % (fileName, file.errorString()))
         return False
     #self.document().commandsChanged.connect(self.documentWasModified)
     return True
Example #13
0
 def refresh(self):
     """
     Public method to refresh the tree.
     """
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.__itemChangingBlock = True
     self.clear()
     
     boldFont = QFont()
     boldFont.setBold(True)
     
     self.__topItem = QTreeWidgetItem(self)
     self.__topItem.setText(0, self.__subscription.title())
     self.__topItem.setFont(0, boldFont)
     self.addTopLevelItem(self.__topItem)
     
     allRules = self.__subscription.allRules()
     
     index = 0
     for rule in allRules:
         item = QTreeWidgetItem(self.__topItem)
         item.setText(0, rule.filter())
         item.setData(0, Qt.UserRole, index)
         if self.__subscription.canEditRules():
             item.setFlags(item.flags() | Qt.ItemIsEditable)
         self.__adjustItemFeatures(item, rule)
         index += 1
     
     self.expandAll()
     self.showRule(None)
     self.__itemChangingBlock = False
     QApplication.restoreOverrideCursor()
     QApplication.processEvents()
Example #14
0
        def _onSearchDone():
            QApplication.restoreOverrideCursor()

            self.resultList.clear()
            self.resultList.setRowCount(0)
            self.selectedTorrent = None

            # parse doc
            try:
                doc = fromstring(request.data.decode('utf-8'))
            except XMLSyntaxError:
                self.results = []
                return

            self.results = parseDoc(doc)

            # setup result list
            if self.results == []:
                self.resultList.insertRow(0)
                self.resultList.setItem(0, 0, QTableWidgetItem('No results found'))
                return

            self.resultList.setRowCount(len(self.results))
            for id_, result in enumerate(self.results):
                self.resultList.setItem(id_, 0, QTableWidgetItem(result[0]))
                self.resultList.setItem(id_, 1, QTableWidgetItem(result[2]))
Example #15
0
 def __searchingFinished(self, hits):
     """
     Private slot to handle the end of the search.
     
     @param hits number of hits (integer) (unused)
     """
     QApplication.restoreOverrideCursor()
Example #16
0
 def _collapseAllDirs(self):
     """
     Protected slot to handle the 'Collapse all directories' menu action.
     """
     self._disconnectExpandedCollapsed()
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     QApplication.processEvents()
     # step 1: find last valid index
     vindex = QModelIndex()
     index = self.model().index(0, 0)
     while index.isValid():
         vindex = index
         index = self.indexBelow(index)
     
     # step 2: go up collapsing all directory items
     index = vindex
     while index.isValid():
         itm = self.model().item(index)
         if (isinstance(itm, ProjectBrowserSimpleDirectoryItem) or
             isinstance(itm, ProjectBrowserDirectoryItem)) and \
            self.isExpanded(index):
             self.collapse(index)
         index = self.indexAbove(index)
     self.layoutDisplay()
     self._connectExpandedCollapsed()
     QApplication.restoreOverrideCursor()
Example #17
0
    def accept(self):
        print("Call to Ok.")

        # Get the datetime from Gui
        self.desdeText = self.ui.fechaDesde.text()
        self.hastaText = self.ui.fechaHasta.text()

        # Set cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # Run
        client = Client(wsdl=self.WSDL_URL)
        self.xmlResponse = client.service.GetServiciosPorVehiculo(login=self.LOGIN, password=self.PASSWORD, fechaDesde=self.desdeText, fechaHasta=self.hastaText)
        print(self.xmlResponse)

        # to database
        self.uploadToPosgreSQL()

        # Get the vehicles id
        self.xmlResponse = client.service.GetVehiculos(login=self.LOGIN, password=self.PASSWORD)
        print(self.xmlResponse)

        # to database
        self.uploadVehiclesToPosgreSQL()

        # Get the vehicles id
        self.xmlResponse = client.service.GetPosicionesGPS(login=self.LOGIN, password=self.PASSWORD, fechadesde=self.desdeText, fechahasta=self.hastaText)
        print(self.xmlResponse)

        # to database
        self.uploadGPSToPosgreSQL()

        # Default cursor
        QApplication.restoreOverrideCursor()
Example #18
0
 def searchId(self, id, stype):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     title_field = 'name'
     if stype == 'movie':
         cap = CapCinema
         title_field = 'original_title'
     elif stype == 'person':
         cap = CapCinema
     elif stype == 'torrent':
         cap = CapTorrent
     elif stype == 'subtitle':
         cap = CapSubtitle
     if '@' in id:
         backend_name = id.split('@')[1]
         id = id.split('@')[0]
     else:
         backend_name = None
     for backend in self.weboob.iter_backends():
         if backend.has_caps(cap) and ((backend_name and backend.name == backend_name) or not backend_name):
             exec('object = backend.get_%s(id)' % (stype))
             if object:
                 func_display = 'self.display' + stype[0].upper() + stype[1:]
                 exec("self.doAction('Details of %s \"%%s\"' %% object.%s, %s, [object, backend])" %
                         (stype, title_field, func_display))
     QApplication.restoreOverrideCursor()
Example #19
0
 def _selectEntries(self, local=True, filter=None):
     """
     Protected method to select entries based on their VCS status.
     
     @param local flag indicating local (i.e. non VCS controlled)
         file/directory entries should be selected (boolean)
     @param filter list of classes to check against
     """
     if self.project.vcs is None:
         return
     
     if local:
         compareString = \
             QCoreApplication.translate('ProjectBaseBrowser', "local")
     else:
         compareString = self.project.vcs.vcsName()
     
     # expand all directories in order to iterate over all entries
     self._expandAllDirs()
     
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     QApplication.processEvents()
     self.selectionModel().clear()
     QApplication.processEvents()
     
     # now iterate over all entries
     startIndex = None
     endIndex = None
     selectedEntries = 0
     index = self.model().index(0, 0)
     while index.isValid():
         itm = self.model().item(index)
         if self.wantedItem(itm, filter) and \
            compareString == itm.data(1):
             if startIndex is not None and \
                startIndex.parent() != index.parent():
                 self._setItemRangeSelected(startIndex, endIndex, True)
                 startIndex = None
             selectedEntries += 1
             if startIndex is None:
                 startIndex = index
             endIndex = index
         else:
             if startIndex is not None:
                 self._setItemRangeSelected(startIndex, endIndex, True)
                 startIndex = None
         index = self.indexBelow(index)
     if startIndex is not None:
         self._setItemRangeSelected(startIndex, endIndex, True)
     QApplication.restoreOverrideCursor()
     QApplication.processEvents()
     
     if selectedEntries == 0:
         E5MessageBox.information(
             self,
             QCoreApplication.translate(
                 'ProjectBaseBrowser', "Select entries"),
             QCoreApplication.translate(
                 'ProjectBaseBrowser',
                 """There were no matching entries found."""))
Example #20
0
 def __finish(self):
     """
     Private slot called when the process finished or the user pressed
     the button.
     """
     QApplication.restoreOverrideCursor()
     self.inputGroup.setEnabled(False)
     self.inputGroup.hide()
     
     if self.paras == 0:
         self.contents.insertPlainText(
             self.tr('There is no difference.'))
         return
     
     self.buttonBox.button(QDialogButtonBox.Save).setEnabled(True)
     self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
     self.buttonBox.button(QDialogButtonBox.Close).setFocus(
         Qt.OtherFocusReason)
     
     tc = self.contents.textCursor()
     tc.movePosition(QTextCursor.Start)
     self.contents.setTextCursor(tc)
     self.contents.ensureCursorVisible()
     
     self.filesCombo.addItem(self.tr("<Start>"), 0)
     self.filesCombo.addItem(self.tr("<End>"), -1)
     for oldFile, newFile, pos in sorted(self.__fileSeparators):
         if oldFile != newFile:
             self.filesCombo.addItem(
                 "{0}\n{1}".format(oldFile, newFile), pos)
         else:
             self.filesCombo.addItem(oldFile, pos)
Example #21
0
 def reset(self):
     """!@brief Simply remove progressBar and reset cursor
     """
     # Remove progressBar and back to default cursor
     self.iface.messageBar().clearWidgets()
     self.iface.mapCanvas().refresh()
     QApplication.restoreOverrideCursor()
Example #22
0
    def searchId(self, id, stype):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        title_field = 'name'
        if stype == 'movie':
            cap = CapCinema
            title_field = 'original_title'
        elif stype == 'person':
            cap = CapCinema
        elif stype == 'torrent':
            cap = CapTorrent
        elif stype == 'subtitle':
            cap = CapSubtitle
        if '@' in id:
            backend_name = id.split('@')[1]
            id = id.split('@')[0]
        else:
            backend_name = None
        for backend in self.weboob.iter_backends():
            if backend.has_caps(cap) and ((backend_name and backend.name == backend_name) or not backend_name):
                object = getattr(backend, 'get_%s' % stype)(id)
                if object:
                    func_name = 'display' + stype[0].upper() + stype[1:]
                    func = getattr(self, func_name)
                    title = getattr(object, title_field)
                    self.doAction('Details of %s %r' % (stype, title), func, [object, backend])

        QApplication.restoreOverrideCursor()
Example #23
0
 def openFile(self):
     if settings.get("file_dialog_dir"):
         self.curDir = '~/'
     else:
         self.curDir = settings.get("file_dialog_dir")
     fn = QFileDialog.getOpenFileName(self,
             self.tr("Open File..."), self.curDir,
             self.tr("HTML-Files (*.htm *.html);;All Files (*)"))
     QApplication.setOverrideCursor(Qt.WaitCursor)
     if fn:
         self.lastFolder = os.path.dirname(fn)
         if os.path.exists(fn):
             if os.path.isfile(fn):
                 f = QFile(fn)
                 if not f.open(QIODevice.ReadOnly |
                               QIODevice.Text):
                     QtGui.QMessageBox.information(self.parent(),
                     self.tr("Error - Lector"),
                     self.tr("Can't open '%s.'" % fn))
                 else:
                     stream = QTextStream(f)
                     text = stream.readAll()
                     self.setText(text)
             else:
                 QMessageBox.information(self.parent(),
                 self.tr("Error - Lector"),
                 self.tr("'%s' is not a file." % fn))
     QApplication.restoreOverrideCursor()
    def __set_mouse_cursor(self, cursor):
        """"""

        # pop from cursor stack
        QApplication.restoreOverrideCursor()

        QApplication.setOverrideCursor(cursor)
        self.current_cursor = cursor
    def hoverLeaveEvent(self, event):
        """
        Restore the previous cursor when leaving this widget
        """
        QApplication.restoreOverrideCursor()
        QApplication.restoreOverrideCursor()

        super().hoverLeaveEvent(event)
Example #26
0
 def biography(self):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.backend.fill_person(self.person, 'biography')
     bio = self.person.biography
     self.ui.shortBioPlain.setPlainText(u'%s' % bio)
     self.ui.biographyLabel.setText('Full biography:')
     self.ui.biographyButton.hide()
     QApplication.restoreOverrideCursor()
Example #27
0
 def show_permission_error(self):
     """
     Show a warning message telling the user that the saving operation
     has failed.
     """
     QApplication.restoreOverrideCursor()
     msg = "The file is in use by another application or user."
     QMessageBox.warning(self, 'Warning', msg, QMessageBox.Ok)
Example #28
0
        def try_loading_project(filename):
            def show_load_error(error):
                QApplication.restoreOverrideCursor()
                self._show_load_error(error)

            with rescue(on_error=show_load_error):
                QApplication.setOverrideCursor(Qt.WaitCursor)
                on_load_project(filename)
                QApplication.restoreOverrideCursor()
Example #29
0
 def onCrossValiation(self):
     self.requestDataUpdate.emit()
     if self.features is None:
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.crossValidation()
     finally:
         QApplication.restoreOverrideCursor()
    def mouseReleaseEvent(self, event):

        if self._has_moved:
            self.Signaller.signalHasMoved.emit(self.pos())
            #self._has_moved=False

            self._has_moved=False
        QApplication.restoreOverrideCursor()
        return QGraphicsRectItem.mouseReleaseEvent(self, event)
Example #31
0
    def adjust_mouse_cursor(self, event):
        """

        """

        if self.getInnerRect().contains(event.pos()):
            QApplication.restoreOverrideCursor()
            QApplication.setOverrideCursor(Qt.SizeAllCursor)
        else:
            cursor = Qt.SizeAllCursor

            if self.resizeDirection.horizontal != ResizeDirectionHorizontal.HorzNone:
                cursor = Qt.SizeHorCursor

            if self.resizeDirection.vertical != ResizeDirectionVertical.VertNone:
                cursor = Qt.SizeVerCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Top
                    and self.resizeDirection.horizontal
                    == ResizeDirectionHorizontal.Left):
                cursor = Qt.SizeFDiagCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Bottom
                    and self.resizeDirection.horizontal
                    == ResizeDirectionHorizontal.Right):
                cursor = Qt.SizeFDiagCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Top
                    and self.resizeDirection.horizontal
                    == ResizeDirectionHorizontal.Right):
                cursor = Qt.SizeBDiagCursor

            if (self.resizeDirection.vertical == ResizeDirectionVertical.Bottom
                    and self.resizeDirection.horizontal
                    == ResizeDirectionHorizontal.Left):
                cursor = Qt.SizeBDiagCursor

            self.__set_mouse_cursor(cursor)
Example #32
0
    def start(self, venvName):
        """
        Public method to start the command.
        
        @param venvName name of the environment to act upon
        @type str
        """
        self.requirementsEdit.clear()
        self.__requirementsAvailable = False

        interpreter = self.__pip.getVirtualenvInterpreter(venvName)
        if not interpreter:
            return

        args = ["-m", "pip", "freeze"]
        if self.localCheckBox.isChecked():
            args.append("--local")
        if self.requirementsFilePicker.text():
            fileName = Utilities.toNativeSeparators(
                self.requirementsFilePicker.text())
            if os.path.exists(fileName):
                args.append("--requirement")
                args.append(fileName)

        QApplication.setOverrideCursor(Qt.WaitCursor)
        success, output = self.__pip.runProcess(args, interpreter)

        if success:
            self.requirementsEdit.setPlainText(output)
            self.__requirementsAvailable = True
        else:
            self.requirementsEdit.setPlainText(
                self.tr("No output generated by 'pip freeze'."))

        QApplication.restoreOverrideCursor()
        self.__updateButtons()

        self.__requirementsEdited = False
Example #33
0
    def exportSource(self):
        """
        Public method performing the export.
        """
        filename = self._getFileName(self.tr("ODT Files (*.odt)"))
        if not filename:
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        QApplication.processEvents()

        tabSize = Preferences.getEditor("TabWidth")
        if tabSize == 0:
            tabSize = 4
        wysiwyg = Preferences.getEditorExporter("ODT/WYSIWYG")
        onlyStylesUsed = Preferences.getEditorExporter("ODT/OnlyStylesUsed")
        tabs = Preferences.getEditorExporter("ODT/UseTabs")

        # generate HTML of the source
        generator = HTMLGenerator(self.editor)
        html = generator.generate(tabSize=tabSize,
                                  useTabs=tabs,
                                  wysiwyg=wysiwyg,
                                  folding=False,
                                  onlyStylesUsed=onlyStylesUsed,
                                  titleFullPath=False)

        # convert HTML to ODT
        doc = QTextDocument()
        doc.setHtml(html)
        writer = QTextDocumentWriter(filename)
        ok = writer.write(doc)
        QApplication.restoreOverrideCursor()
        if not ok:
            E5MessageBox.critical(
                self.editor, self.tr("Export source"),
                self.tr("""<p>The source could not be exported to"""
                        """ <b>{0}</b>.</p>""").format(filename))
Example #34
0
 def save_mesh_file(self):
     #if defined(WIN32)
     #    QApplication::setOverrideCursor(Qt::WaitCursor)
     #endif
     '''
     Data::Mesh::PointMesh    * pmesh = ( cur_dock == 0 ) ? 0 : cur_dock.GetPointMesh()
     Data::Mesh::SolidMesh    * smesh = ( cur_dock == 0 ) ? 0 : cur_dock.GetSolidMesh()
     Data::FiberDirectionData * fdata = ( cur_dock == 0 ) ? 0 : cur_dock.GetFiberData()
 
     if( pmesh ){
         QString save_file = saveDialog( tr('Save to Point File'), QString('Point File (*.point *.point.gz)') )
         if(save_file.size() > 0 ){
             pmesh.Save( save_file.toLocal8Bit().data(), save_file.endsWith( tr('.gz') ) )
         }
     }
 
     if( dynamic_cast<Data::Mesh::TetMesh*>(smesh) != 0 ){
         QString save_file = saveDialog( tr('Save to Tets File'), QString('Binary Tets File (*.btet *.btet.gz)') )
         if(save_file.size() > 0){
             smesh.Save( save_file.toLocal8Bit().data() )
         }
     }
 
     if( dynamic_cast<Data::Mesh::HexMesh*>(smesh) != 0 ){
         QString save_file = saveDialog( tr('Save Hex File'), QString('Binary Hex File (*.bhex)') )
         if(save_file.size() > 0){
             smesh.Save( save_file.toLocal8Bit().data() )
         }
     }
 
     if( fdata ){
         QString save_file = saveDialog( tr('Save to Fiber File'), QString('Fiber File (*.fibs)') )
         if(save_file.size() > 0 ){
             fdata.Save( save_file.toLocal8Bit().data() )
         }
     }
     '''
     QApplication.restoreOverrideCursor()
Example #35
0
    def accept(self):
        if self.radio_contact.isChecked():
            index = self.combo_contact.currentIndex()
            pubkey = self.account.contacts[index]['pubkey']
        else:
            pubkey = self.edit_pubkey.text()

        password = self.password_asker.exec_()
        if password == "":
            return

        try:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            self.account.certify(password, self.community, pubkey)
            toast.display(
                self.tr("Certification"),
                self.tr("Success certifying {0} from {1}").format(
                    pubkey, self.community.currency))
        except ValueError as e:
            QMessageBox.critical(
                self, self.tr("Certification"),
                self.tr("Something wrong happened : {0}").format(e),
                QMessageBox.Ok)
            return
        except NoPeerAvailable as e:
            QMessageBox.critical(
                self, self.tr("Certification"),
                self.tr("Couldn't connect to network : {0}").format(e),
                QMessageBox.Ok)
            return
        except Exception as e:
            QMessageBox.critical(self, self.tr("Error"), "{0}".format(e),
                                 QMessageBox.Ok)
            return
        finally:
            QApplication.restoreOverrideCursor()

        super().accept()
Example #36
0
    async def accept(self):
        logging.debug("Accept transfer action...")
        self.view.button_box.setEnabled(False)
        comment = self.view.edit_message.text()

        logging.debug("checking recipient mode...")
        recipient = self.selected_pubkey()
        amount = self.view.spinbox_amount.value() * 100
        amount_base = self.model.current_base()

        logging.debug("Showing password dialog...")
        secret_key, password = self.password_input.get_salt_password()

        logging.debug("Setting cursor...")
        QApplication.setOverrideCursor(Qt.WaitCursor)

        logging.debug("Send money...")
        result, transactions = await self.model.send_money(
            recipient, secret_key, password, amount, amount_base, comment)
        if result[0]:
            await self.view.show_success(self.model.notifications(), recipient)
            logging.debug("Restore cursor...")
            QApplication.restoreOverrideCursor()
            self.view.button_box.setEnabled(True)

            # If we sent back a transaction we cancel the first one
            self.model.cancel_previous()
            for tx in transactions:
                self.model.app.new_transfer.emit(self.model.connection, tx)
            self.view.clear()
            self.rejected.emit()
        else:
            await self.view.show_error(self.model.notifications(), result[1])
            for tx in transactions:
                self.model.app.new_transfer.emit(self.model.connection, tx)

            QApplication.restoreOverrideCursor()
            self.view.button_box.setEnabled(True)
Example #37
0
        def get_data():
            # Download files
            download_only = False
            if check1.isChecked():
                download_only = True

            # Find the selected files
            remote_file_list = []
            for m in self.file_box1.selectedIndexes():
                remote_file_list.append(m.data())
            if len(remote_file_list) < 1:
                title = "No files"
                msg = "Please select some files to download."
                show_my_message(title, msg)
                return
            # Load downloaded files into pytplot
            result = []
            if len(remote_file_list) < 1:
                msg = "No files to download."
                show_my_message(title, msg)
                return

            self.local_dir = self.dir_box.text()

            QApplication.setOverrideCursor(Qt.WaitCursor)
            result = download_and_load(remote_file_list, self.local_dir,
                                       download_only)
            QApplication.restoreOverrideCursor()

            reslen = len(result)
            if reslen > 0:
                msg = "Donwload complete. Number of files: " + str(reslen)
            else:
                msg = "No files were downloaded."

            title = 'Download Files'
            show_my_message(title, msg)
            self.parent.statusbar.showMessage('Status: ' + msg)
Example #38
0
    def __init__(self, book, status_bar):
        self.status_bar = status_bar
        self.install_directory = os.getcwd()

        filename = ""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("PDF (*.pdf);;All (*)")
        dialog.setWindowTitle("Create PDF")
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setDirectory(book.source_path)
        dialog.setDefaultSuffix("pdf")
        if dialog.exec_():
            filename = dialog.selectedFiles()[0]
        del dialog
        if not filename:
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        html = "<html>\n<head>\n"
        html += "<link href=\"file://" + os.path.join(
            book.source_path, "css",
            "pastie.css") + "\" rel=\"stylesheet\" type=\"text/css\"/>\n"
        html += "<link href=\"file://" + os.path.join(
            book.source_path, "css",
            "stylesheet.css") + "\" rel=\"stylesheet\" type=\"text/css\"/>\n"
        html += "</head>\n<body>\n"
        toc, htm, html = generateParts(book, html)
        html += generateToc(book, toc)
        html += "<p style=\"page-break-before: always\">"
        html += htm
        html += "\n</body>\n</html>"
        h = HTML(string=html)
        css = CSS(string='@page { size: A5; margin: 0cm }')
        h.write_pdf(filename, stylesheets=[css])
        QApplication.restoreOverrideCursor()
        self.status_bar.showMessage("Ready")
Example #39
0
    def on_accepted(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)

        iq_data, sample_rate = self.parse_csv_file(self.filename, self.ui.comboBoxCSVSeparator.currentText(),
                                                   self.ui.spinBoxIDataColumn.value()-1,
                                                   self.ui.spinBoxQDataColumn.value()-1,
                                                   self.ui.spinBoxTimestampColumn.value()-1)

        target_filename = self.filename.rstrip(".csv")
        if os.path.exists(target_filename + ".complex"):
            i = 1
            while os.path.exists(target_filename + "_" + str(i) + ".complex"):
                i += 1
        else:
            i = None

        target_filename = target_filename if not i else target_filename + "_" + str(i)
        target_filename += ".complex"

        iq_data.tofile(target_filename)

        self.data_imported.emit(target_filename, sample_rate if sample_rate is not None else 0)
        QApplication.restoreOverrideCursor()
Example #40
0
    def createElement(self, layerName, complementary=False):
        layer = "" if complementary else layerName
        complLayer = layerName if complementary else ""
        # Process
        QApplication.setOverrideCursor(Qt.WaitCursor)
        resMessage = GISRed.CreateLayer(self.ProjectDirectory,
                                        self.NetworkName, layer, complLayer)
        QApplication.restoreOverrideCursor()

        if resMessage == "True":
            self.parent.openElementLayer(layerName)
        elif resMessage == "False":
            self.iface.messageBar().pushMessage(
                "Warning",
                "Some issues occurred in the process",
                level=1,
                duration=5)
        else:
            self.iface.messageBar().pushMessage("Error",
                                                resMessage,
                                                level=2,
                                                duration=5)
        self.close()
Example #41
0
    def loadFromFile(self, fileName):
        f = QFile(fileName)
        if not f.open(QFile.ReadOnly):
            model = QStringListModel()
            self._completer.setModel(model)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        words = []
        while not f.atEnd():
            line = f.readLine().trimmed()
            if line.length() != 0:
                try:
                    line = str(line, encoding='utf-8')
                except TypeError:
                    line = str(line)

                words.append(line)

        QApplication.restoreOverrideCursor()

        model = QStringListModel(words)
        self._completer.setModel(model)
Example #42
0
    def newProfile(self):
        name = ''
        while True:
            name, ok = QInputDialog.getText(
                self._parent, _('Add Profile'),
                _('Please enter the name of the profile') + ':',
                text=name)
            if not ok:
                return

            QApplication.setOverrideCursor(Qt.WaitCursor)
            try:
                id = hwctool.settings.profileManager.addProfile(name)
                self.addProfile(id, name, False)
                self.selectProfile(id)
            except Exception as e:
                QMessageBox.information(self._parent, _(
                    "Please enter a valid name"), str(e))
                module_logger.exception("message")
                continue
            finally:
                QApplication.restoreOverrideCursor()
            return
Example #43
0
    def exportProfile(self):
        current = hwctool.settings.profileManager.current()
        filename = os.path.join(
            hwctool.settings.profileManager.basedir(),
            'hwct-profile-{}-{}.zip'.format(current['name'],
                                            time.strftime("%Y%m%d"))
        )
        filename, ok = QFileDialog.getSaveFileName(
            self._parent, 'Export Profile',
            filename, _("ZIP archive") + " (*.zip)")
        if not ok:
            return

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self._controller.saveAll()
            hwctool.settings.profileManager.exportProfile(
                current['id'], filename)
        except Exception as e:
            QMessageBox.critical(self._parent, _("Error"), str(e))
            module_logger.exception("message")
        finally:
            QApplication.restoreOverrideCursor()
Example #44
0
 def renameProfile(self):
     profile = hwctool.settings.profileManager.current()
     name = profile.get('name', '')
     while True:
         name, ok = QInputDialog.getText(
             self._parent, _('Rename Profile'),
             _('Please enter the name of the profile') + ':',
             text=name)
         if not ok:
             return
         QApplication.setOverrideCursor(Qt.WaitCursor)
         try:
             hwctool.settings.profileManager.renameProfile(
                 profile['id'], name)
             self._profiles[profile['id']].setText(name)
         except Exception as e:
             QMessageBox.information(self._parent, _(
                 "Please enter a valid name"), str(e))
             module_logger.exception("message")
             continue
         finally:
             QApplication.restoreOverrideCursor()
         return
Example #45
0
    def select_export_file(self, time_frame, savefilename=None):
        """
        Prompt a dialog to select a file and save the weather data time series
        to a file in the specified format and time frame.
        """
        if savefilename is None:
            savefilename = osp.join(
                self.dialog_dir, 'Weather%s_%s' %
                (time_frame.capitalize(), self.model['Station Name']))

        savefilename = self.select_savefilename('Export %s' % time_frame,
                                                savefilename,
                                                '*.xlsx;;*.xls;;*.csv')

        if savefilename:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            QApplication.processEvents()
            try:
                self.model.export_dataset_to_file(savefilename, time_frame)
            except PermissionError:
                self.show_permission_error()
                self.select_export_file(time_frame, savefilename)
            QApplication.restoreOverrideCursor()
Example #46
0
    def find(self, text, default_epsg):
        # Find text
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            self.geofinder_dict_list = self.geofinder.find(text, default_epsg)
        finally:
            QApplication.restoreOverrideCursor()

        # If we have a rectangle, we do not have to do anything, we get the coordinates and access
        if self.geofinder.is_rectangle(self.geofinder_dict_list):
            # Get rectangle coordinates
            self.selected = 0        
        else:
            # We show the found places in a dialog
            self.set_data(self.geofinder_dict_list)
            if not self.do_modal():
                return False
            self.selected = self.get_selection_index()
            if self.selected < 0:
                return False
            print("Selected: %s" % self.geofinder_dict_list[self.selected]['nom'])

        return True 
Example #47
0
    def _reloadDocument(self, document):
        """Reload the document contents
        """
        if document.qutepart.document().isModified():
            template = self.tr("The file <b>%s</b> has been modified by you.\n"
                               "Do you want to reload and discard changes?")
            text = template % document.fileName()
            ret = QMessageBox.question(core.mainWindow(),
                                       self.tr("Reload file..."), text,
                                       QMessageBox.Yes | QMessageBox.No,
                                       QMessageBox.No)
            if ret != QMessageBox.Yes:
                return

        # open file
        try:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            document.reload()
        except IOError as ex:
            QMessageBox.critical(None, self.tr("File not reloaded"), str(ex))
            return None
        finally:
            QApplication.restoreOverrideCursor()
Example #48
0
def exceptionHook(type, value, backtrace):
    from PyQt5.QtWidgets import QApplication
    from Koo.Common.Version import Version
    cursor = QApplication.overrideCursor()
    if cursor:
        QApplication.restoreOverrideCursor()
    from .Settings import Settings
    import traceback

    sentry_dsn = Settings.get("client.sentry_dsn")
    if sentry_dsn:
        client = Client(sentry_dsn)

        extra = Settings.options
        extra.update({"version": Version})
        client.captureException(exc_info=(type, value, backtrace), extra=extra)

    backtrace = ''.join(traceback.format_tb(backtrace))
    if Settings.value('client.debug'):
        from Koo.Common import Notifier
        Notifier.notifyError(type, value, backtrace)
    else:
        error('Error: %s\n%s\n%s' % (type, value, backtrace))
Example #49
0
    def createProject(self):
        epsg = self.crs.authid().replace("EPSG:", "")
        units = self.cbUnits.currentText()
        headloss = self.cbHeadloss.currentText()
        # Process
        QApplication.setOverrideCursor(Qt.WaitCursor)
        resMessage = GISRed.CreateProject(self.ProjectDirectory, self.NetworkName, epsg, units, headloss)
        QApplication.restoreOverrideCursor()

        # Message
        if not resMessage == "True":
            if resMessage == "False":
                self.iface.messageBar().pushMessage("Warning", "Some issues occurred in the process", level=1, duration=5)
            else:
                self.iface.messageBar().pushMessage("Error", resMessage, level=2, duration=5)
            self.close()
            return False

        # Write .gql file
        file = open(self.gplFile, "a+")
        QGISRedUtils().writeFile(file, self.NetworkName + ";" + self.ProjectDirectory + '\n')
        file.close()
        return True
Example #50
0
 def on_btnAddUser_clicked(self):
     """
     Give the user selected from the combobox the role
     """
     addUser = self.cbUserName.currentText()
     currentUsers = [
         str(self.lstRoleUsers.item(i).text())
         for i in range(self.lstRoleUsers.count())
     ]
     if addUser in currentUsers:
         # error, the user already has the selected role
         self.helper.displayErrMsg("Edit Role",
                                   "The role already has this user.")
     else:
         # give the role the user
         QApplication.setOverrideCursor(Qt.WaitCursor)
         rc, msg = self.parent.schemaModel.addUserRole(userName=addUser,
                                                       role=self.roleName)
         if rc:
             self.lstRoleUsers.addItem(addUser)
         else:
             self.helper.displayErrMsg("Add User to Role Error", msg)
         QApplication.restoreOverrideCursor()
Example #51
0
 def mouseReleaseEvent(self, ev):
     QApplication.restoreOverrideCursor()
     x = False
     y = False
     if self.x() + self.width() > self.desktopWidget.width():
         self.move(self.desktopWidget.width() - self.width(), self.y())
         x = True
     elif self.x() < 0:
         self.move(0, self.y())
         x = True
     if x and self.halfScreenHeight() - 64 <= self.y(
     ) <= self.halfScreenHeight() + 64:
         self.move(self.x(), self.halfScreenHeight())
     if self.y() < 0:
         self.move(self.x(), 0)
         y = True
     elif self.y() + self.height() > self.desktopWidget.height():
         self.move(self.x(), self.desktopWidget.height() - self.height())
         y = True
     if y and self.halfScreenWidth() - 64 <= self.x(
     ) <= self.halfScreenWidth() + 64:
         self.move(self.halfScreenWidth(), self.y())
     return QToolBar.mouseReleaseEvent(self, ev)
Example #52
0
 def paintData(self, printer):
     """Paint data to be printed to the printer.
     """
     pageNum = 1
     try:
         maxPageNum = self.outputGroup[-1].pageNum
     except IndexError:  # printing empty branch
         maxPageNum = 1
     if self.printer.printRange() != QPrinter.AllPages:
         pageNum = self.printer.fromPage()
         maxPageNum = self.printer.toPage()
     painter = QPainter()
     if not painter.begin(self.printer):
         QMessageBox.warning(QApplication.activeWindow(), 'TreeLine',
                             _('Error initializing printer'))
     QApplication.setOverrideCursor(Qt.WaitCursor)
     while True:
         self.paintPage(pageNum, painter)
         if pageNum == maxPageNum:
             QApplication.restoreOverrideCursor()
             return
         pageNum += 1
         self.printer.newPage()
Example #53
0
    def load_file_content(self, fname):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        QApplication.processEvents()
        self.metadata_root.clear_widget()
        self.ui.actionData_Quality.setChecked(True)
        self.use_dataqual(True)
        self.ui.actionSpatial.setChecked(True)
        self.use_spatial(True)
        self.ui.actionEntity_and_Attribute.setChecked(True)
        self.use_eainfo(True)
        self.ui.actionDistribution.setChecked(True)
        self.use_distinfo(True)
        try:
            new_record = xml_utils.fname_to_node(fname)
            self.metadata_root.from_xml(new_record)
            self.statusBar().showMessage("File loaded", 10000)
        except BaseException as e:
            import traceback

            msg = "Cannot open file %s:\n%s." % (fname, traceback.format_exc())
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, "Recent Files", msg)
        QApplication.restoreOverrideCursor()
Example #54
0
 def loadBinary(self, filename):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     if self.treeView.manifest.compression == 'gzip':
         reader = gzip.open
     elif self.treeView.manifest.compression == 'bz2':
         reader = bz2.BZ2File
     else:
         reader = open
     try:
         with reader(filename, 'rb') as f:
             data = f.read()
         self.qHexEdit.setData(data)
         self._current_filename = filename
         self.statusBar.showMessage(
             self.tr("Loaded binary: ") + os.path.basename(filename),
             STATUSBAR_TIMEOUT)
         self.refreshTitle()
     except IOError as e:
         QErrorMessage(self).showMessage(self.tr('Format Error: ') + str(e))
         logger.exception(e)
     finally:
         self.treeView.refresh_view()
         QApplication.restoreOverrideCursor()
Example #55
0
 def open_output_file(self):
     QApplication.restoreOverrideCursor()
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     TDialog = QFileDialog()
     fileName, _ = TDialog.getSaveFileName(self.parent,"Save file as:", BS.lastdir, self.file_filter, options=options)
     if fileName:
         self.file = QFile(fileName)
         BS.lastdir = QFileInfo(fileName).absolutePath()
         if not self.file.open(QFile.WriteOnly | QFile.Text):  # open to write
             mb = QMessageBox()
             mb.setTextFormat(Qt.RichText)
             mb.setText("<p style='font-size: 18pt'>Open File error</p>"
                        "<p style='font-size: 14pt; font-weight: normal'> Can't open file <i>{}</i> for writing.<br><br>"
                        " File error was: \"{}\".</p>".format(fileName, self.file.errorString()))
             mb.setIcon(QMessageBox.Warning)
             mb.exec()
             return False
         else:
             self.outstream = QTextStream(self.file)
             return True
     else:
         return False
    def onConnectBtnClicked(self):
        CSCChangeListCreator.infos = []
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.te_message.clear()
        if self.validateInput():
            try:
                if self.connecToPerforce():
                    infos = []
                    collect_sale_thread = Thread(target=self.getRepoDataInfo,
                                                 args=[infos])
                    collect_sale_thread.start()
                    collect_sale_thread.join()
                    CSCChangeListCreator.infos = infos
                    log_notice(
                        "Connection is established successfully. Click 'Create' button to create change list!"
                    )
                    self.le_sales.setEnabled(True)
                    self.le_directory.setEnabled(True)
                    self.cb_file_name.setEnabled(True)
            except CSCRepoException as e:
                log_error(str(e))

        QApplication.restoreOverrideCursor()
Example #57
0
    def draw_hydrograph(self):
        if self.dmngr.wldataset_count() == 0:
            msg = 'Please import a valid water level data file first.'
            self.ConsoleSignal.emit('<font color=red>%s</font>' % msg)
            self.emit_warning(msg)
            return

        self.update_graph_layout_parameter()

        # Generate and Display Graph :

        for i in range(5):
            QCoreApplication.processEvents()

        QApplication.setOverrideCursor(Qt.WaitCursor)

        self.hydrograph.set_wldset(self.dmngr.get_current_wldset())
        self.hydrograph.set_wxdset(self.dmngr.get_current_wxdset())
        self.hydrograph.generate_hydrograph()

        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)

        QApplication.restoreOverrideCursor()
Example #58
0
    def import_mesh_file(self):
        if self.cur_dock == 0:
            return

        #if defined(WIN32)
        #    QApplication::setOverrideCursor(Qt::WaitCursor)
        #endif

        smesh = 0  #Data::Mesh::SolidMesh
        pmesh = 0  #Data::Mesh::PointMesh

        pmesh = HeartDock.OpenPointMesh()

        if pmesh:
            smesh = HeartDock.OpenSolidMesh()
            self.cur_dock.AddImportedMesh(pmesh, smesh)
        else:
            if pmesh:
                pmesh = 0
            if smesh:
                smesh = 0

        QApplication.restoreOverrideCursor()
Example #59
0
 def initialLoad(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     splash = QLabel(self)
     pixmap = QPixmap(
         os.path.join(os.path.dirname(__file__), "iss013-e-14802.jpg"))
     #print(os.path.join(os.path.dirname(__file__),
     #        "iss013-e-14802.jpg"))
     splash.setPixmap(pixmap)
     splash.setWindowFlags(Qt.SplashScreen)
     splash.move(self.x() + ((self.width() - pixmap.width()) / 2),
                 self.y() + ((self.height() - pixmap.height()) / 2))
     splash.show()
     QApplication.processEvents()
     try:
         self.model.load()
     except IOError as e:
         # QMessageBox.warning(self, "Water Quality - Error", e)
         print("Water Quality - Error", e)
     else:
         self.tableView.resizeColumnsToContents()
     splash.close()
     QApplication.processEvents()
     QApplication.restoreOverrideCursor()
Example #60
0
    def _handle_password_validated(self, valid: bool):
        self.valid = valid

        QApplication.restoreOverrideCursor()
        tries_ended = self.tries == self.max_tries

        if not self.valid:
            self.label_error.show()
            self.bt_cancel.setEnabled(True)

            if tries_ended:
                self.bt_cancel.setText(self.i18n['close'].capitalize())
                self.label_error.setText(
                    self.i18n['popup.root.bad_password.last_try'])
                self.bt_cancel.setFocus()
            else:
                self.label_error.setText(
                    self.i18n['popup.root.bad_password.body'])
                self.bt_ok.setEnabled(True)
                self.input_password.setEnabled(True)
                self.input_password.setFocus()
        else:
            self.close()