コード例 #1
0
def load_stylesheet_pyqt5():
    """
    Loads the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #353434;
                text-align: center;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
コード例 #2
0
ファイル: gcode.py プロジェクト: Paul2M-SP3D/PrusaControl
    def load_gcode_file(self):
        file = QFile(self.filename)
        file.open(QIODevice.ReadOnly | QIODevice.Text)
        in_stream = QTextStream(file)
        file_size = file.size()
        counter = 0
        line = 0
        line_number = 0
        while not in_stream.atEnd() and self.is_running is True:

            counter += 1
            if self.set_update_progress and counter == 10000:
                #in_stream.pos() je hodne pomala funkce takze na ni pozor!!!
                progress = (in_stream.pos() * 1. / file_size * 1.) * 100.
                self.set_update_progress.emit(int(progress))
                counter = 0

            line = in_stream.readLine()
            bits = line.split(';', 1)
            if bits[0] == '':
                line_number += 1
                continue
            if 'G1 ' in bits[0]:
                self.parse_g1_line(bits, line_number)
            else:
                line_number += 1
                continue
            line_number += 1

        if self.is_running is False:
            self.set_update_progress.emit(0)

        self.printing_time = self.calculate_time_of_print()
        self.filament_length = 0.0  # self.calculate_length_of_filament()

        ###
        self.non_extruding_layers = []
        for i in self.data:
            layer_flag = 'M'
            for l in self.data[i]:
                _start, _end, flag, _speed, _extr, _line = l
                if flag in ['E', 'E-sk', 'E-su', 'E-i', 'E-p']:
                    layer_flag = 'E'
                    break
            if layer_flag == 'M':
                self.non_extruding_layers.append(i)

        for i in self.non_extruding_layers:
            self.data.pop(i, None)

        self.data_keys = set()
        self.data_keys = set(self.data)
        self.data_keys = sorted(self.data_keys, key=float)

        self.set_data_keys.emit(self.data_keys)
        self.set_data.emit(self.data)
        self.set_all_data.emit(self.all_data)
        self.set_printing_time.emit(self.printing_time)

        self.finished.emit()
コード例 #3
0
ファイル: __init__.py プロジェクト: andystopford/StockAle
def load_stylesheet():
    """
    Loads the stylesheet. Takes care of importing the rc module.
    :return the stylesheet string
    """
    import DarkStyle.pyqt_style_rc
    # Load the stylesheet content from resources
    from PyQt4.QtCore import QFile, QTextStream
    f = QFile(":DarkStyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
コード例 #4
0
ファイル: editor.py プロジェクト: nt6/KhtEditor
    def save(self):
        """Hum ... just save ..."""
        if self.filename.startswith("Unnamed"):
            filename = self.parent().parent().parent().saveAsFile()
            if not (filename == ''):
                return
            self.filename = filename
        self.setWindowTitle(QFileInfo(self.filename).fileName())
        exception = None
        filehandle = None
        try:
            #Before FileSave plugin hook
            for plugin in filter_plugins_by_capability('beforeFileSave',
                                                       self.enabled_plugins):
                plugin.do_beforeFileSave(self)

            filehandle = QFile(self.filename)
            if not filehandle.open(QIODevice.WriteOnly):
                raise IOError, unicode(filehandle.errorString())
            stream = QTextStream(filehandle)
            stream.setCodec("UTF-8")
            stream << self.toPlainText()
            self.document().setModified(False)
            RecentFiles().append(self.filename)
        except (IOError, OSError), ioError:
            exception = ioError
コード例 #5
0
ファイル: find_in_files.py プロジェクト: AlexaProjects/Alexa2
    def _grep_file(self, file_path, file_name):
        if not self.by_phrase:
            with open(file_path, 'r') as f:
                content = f.read()
            words = [word for word in
                self.search_pattern.pattern().split('|')]
            words.insert(0, True)

            def check_whole_words(result, word):
                return result and content.find(word) != -1
            if not reduce(check_whole_words, words):
                return
        file_object = QFile(file_path)
        if not file_object.open(QFile.ReadOnly):
            return

        stream = QTextStream(file_object)
        lines = []
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not (stream.atEnd() and not line):
            column = self.search_pattern.indexIn(line)
            if column != -1:
                lines.append((line_index, line))
            #take the next line!
            line = stream.readLine()
            line_index += 1
        #emit a signal!
        relative_file_name = file_manager.convert_to_relative(
            self.root_dir, file_path)
        self.emit(SIGNAL("found_pattern(PyQt_PyObject)"),
            (relative_file_name, lines))
コード例 #6
0
    def _grep_file(self, file_path, file_name):
        """Search for each line inside the file."""
        if not self.by_phrase:
            with open(file_path, 'r') as f:
                content = f.read()
            words = [word for word in self.search_pattern.pattern().split('|')]
            words.insert(0, True)

            def check_whole_words(result, word):
                return result and content.find(word) != -1

            if not reduce(check_whole_words, words):
                return
        file_object = QFile(file_path)
        if not file_object.open(QFile.ReadOnly):
            return

        stream = QTextStream(file_object)
        lines = []
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not (stream.atEnd() and not line):
            column = self.search_pattern.indexIn(line)
            if column != -1:
                lines.append((line_index, line))
            #take the next line!
            line = stream.readLine()
            line_index += 1
        #emit a signal!
        relative_file_name = file_manager.convert_to_relative(
            self.root_dir, file_path)
        self.emit(SIGNAL("found_pattern(PyQt_PyObject)"),
                  (relative_file_name, lines))
コード例 #7
0
ファイル: textedit.py プロジェクト: KimSeojin1204/Python-Docs
 def save(self):
     if self.filename.startsWith("Unnamed"):
         filename = QFileDialog.getSaveFileName(self,
                 "Text Editor -- Save File As", self.filename,
                 "Text files (*.txt *.*)")
         if filename.isEmpty():
             return
         self.filename = filename
     self.setWindowTitle(QFileInfo(self.filename).fileName())
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         stream << self.toPlainText()
         self.document().setModified(False)
     except EnvironmentError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
コード例 #8
0
def style_rc():
    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
コード例 #9
0
    def go_to_definition(self):
        self.dirty = True
        self.results = []
        locations = self.get_locations()
        if self._isVariable:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if (x.type == FILTERS['attribs']) and (x.name == self._search)
            ]
        else:
            preResults = [[
                file_manager.get_basename(x.path), x.path, x.lineno, ''
            ] for x in locations if ((x.type == FILTERS['functions']) or
                                     (x.type == FILTERS['classes'])) and (
                                         x.name.startswith(self._search))]
        for data in preResults:
            file_object = QFile(data[1])
            if not file_object.open(QFile.ReadOnly):
                return

            stream = QTextStream(file_object)
            line_index = 0
            line = stream.readLine()
            while not self._cancel and not stream.atEnd():
                if line_index == data[2]:
                    data[3] = line
                    self.results.append(data)
                    break
                #take the next line!
                line = stream.readLine()
                line_index += 1
        self._search = None
        self._isVariable = None
コード例 #10
0
ファイル: locator.py プロジェクト: AnyBucket/ninja-ide
    def go_to_definition(self):
        self.dirty = True
        self.results = []
        locations = self.get_locations()
        if self._isVariable:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if (x.type == FILTERS['attribs']) and (x.name == self._search)]
        else:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if ((x.type == FILTERS['functions']) or
                    (x.type == FILTERS['classes'])) and
                   (x.name.startswith(self._search))]
        for data in preResults:
            file_object = QFile(data[1])
            if not file_object.open(QFile.ReadOnly):
                return

            stream = QTextStream(file_object)
            line_index = 0
            line = stream.readLine()
            while not self._cancel and not stream.atEnd():
                if line_index == data[2]:
                    data[3] = line
                    self.results.append(data)
                    break
                #take the next line!
                line = stream.readLine()
                line_index += 1
コード例 #11
0
ファイル: tool.py プロジェクト: GVallicrosa/FabQtV2
 def save(self, new):
     fh = QFile("tools/" + self.name + ".tool")
     if new and fh.exists():
         return False
     if fh.open(QIODevice.WriteOnly):
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='%s'?>\n<!DOCTYPE TOOL>\n<TOOL\n" % CODEC)
         stream << (
             "TIPDIAM='%s'\nSYRDIAM='%s'\nPATHWIDTH='%s'\nPATHHEIGHT='%s'\nJOGSPEED='%s'\nSUCKBACK='%s'\nPUSHOUT='%s'\n"
             "PATHSPEED='%s'\nPAUSEPATHS='%s'\nCLEARANCE='%s'\nDEPOSITIONRATE='%s'\n>"
             % (
                 self.tipDiam,
                 self.syrDiam,
                 self.pathWidth,
                 self.pathHeight,
                 self.jogSpeed,
                 self.suckback,
                 self.pushout,
                 self.pathSpeed,
                 self.pausePaths,
                 self.clearance,
                 self.depRate,
             )
         )
         stream << ("\n</TOOL>")
         fh.close()
     return True
コード例 #12
0
ファイル: manejador_de_archivo.py プロジェクト: ekimdev/edis
def escribir_archivo(nombre_de_archivo, contenido):
    """ Se escribe en el archivo, si el nombre no tiene extensión se agrega .c
    """

    extension = (os.path.splitext(nombre_de_archivo)[-1])[1:]
    if not extension:
        nombre_de_archivo += '.c'

    try:
        f = QFile(nombre_de_archivo)
        if not f.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning("Guardar", "No se escribio en %s: %s" % (
                nombre_de_archivo, f.errorString()))

            return False

        flujo = QTextStream(f)
        encode_flujo = flujo.codec().fromUnicode(contenido)
        f.write(encode_flujo)
        f.flush()
        f.close()

    except:
        pass

    return os.path.abspath(nombre_de_archivo)
コード例 #13
0
ファイル: about.py プロジェクト: Guillon88/stdm
    def __init__(self,parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        #Connect signals
        self.btnContactUs.clicked.connect(self.onContactUs)
        self.btnSTDMHome.clicked.connect(self.onSTDMHome)

        #Load about HTML file
        aboutLocation = PLUGIN_DIR + "/html/about.htm"
        if QFile.exists(aboutLocation):
            aboutFile = QFile(aboutLocation)
            if not aboutFile.open(QIODevice.ReadOnly):
                QMessageBox.critical(self,
                                     QApplication.translate("AboutSTDMDialog","Open Operation Error"),
                                     QApplication.translate("AboutSTDMDialog","Cannot read 'About STDM' source file."))
                self.reject()

            reader = QTextStream(aboutFile)
            aboutSTDM = reader.readAll()
            self.txtAbout.setHtml(aboutSTDM)

        else:
            QMessageBox.critical(self,
                                 QApplication.translate("AboutSTDMDialog","File Does Not Exist"),
                                 QApplication.translate("AboutSTDMDialog","'About STDM' source file does not exist."))
            self.reject()
コード例 #14
0
ファイル: main.py プロジェクト: dhirajkhatiwada1/uludag
 def save_file(self):
     """
     Saving file to the path where getting from QFileDialog
     """
     fileobject = None
     if self.path is "":
         self.path = QFileDialog.getSaveFileName(self,
                                             "TextEditor", 
                                             self.tr("unnamed"))
     try:
         fileobject = QFile(self.path)
         if not fileobject.open(QIODevice.WriteOnly):
             raise IOError, unicode(fileobject.errorString())
         textstream = QTextStream(fileobject)
         textstream.setCodec("UTF-8")
         textstream << self.textEdit.toPlainText()
         self.textEdit.document().setModified(False)
         self.setWindowTitle("%s - TextEditor" % 
                             QFileInfo(self.path).fileName())
     except (IOError, OSError), error:
         QMessageBox.warning(self, 
                             self.tr("TextEditor - Save Error"), 
                             self.tr("Unable to save {0}:{1}".format( 
                             self.path, error)))
         self.path = ""
コード例 #15
0
ファイル: __init__.py プロジェクト: guygal/QDarkStyleSheet
def load_stylesheet(pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    if pyside:
        import qdarkstyle.pyside_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        print("Unable to set stylesheet, file not found\n")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        return ts.readAll()
コード例 #16
0
 def parseURLs(self, reply, startFrom):
     """ Get a dict of new IDs:URLs from the current playlist (newURLs) """
     newURLs = {}  # {0:URL0, 1:URL1, ...}
     count = 0     
     
     #Get the delta and start reading it
     allData = reply.readAll()
     allData = allData.right(startFrom) # Get rid of old data
     response = QTextStream(allData, QIODevice.ReadOnly)
     data = response.readLine()
     
     # Parse 
     while (data):     
         data = str(data.split("\n")[0])
         if data:
             if "#" in data: # It's a playlist comment 
                 if self.__endTag in data: 
                     self.__playlistFinished = True 
                 elif self.__exceptionTag in data:
                     if self.DEBUG: print "Exception found!"
                     self.__exceptionFound = True
                     self.__exceptionUrl = data.split(":",1)[1].strip()
             else: 
                 newURLs[count+self.__loadedChunks] = data
                 count += 1
         data = response.readLine()
 
     return newURLs
コード例 #17
0
ファイル: editor.py プロジェクト: khertan/KhtEditor
    def save(self):
        """Hum ... just save ..."""
        if self.filename.startswith("Unnamed"):
            filename = self.parent().parent().parent().saveAsFile()
            if not (filename == ''):
                return
            self.filename = filename
        self.setWindowTitle( QFileInfo(self.filename).fileName())
        exception = None
        filehandle = None
        try:
            #Before FileSave plugin hook
            for plugin in filter_plugins_by_capability('beforeFileSave',self.enabled_plugins):
                plugin.do_beforeFileSave(self)

            filehandle =  QFile(self.filename)
            if not filehandle.open( QIODevice.WriteOnly):
                raise IOError, unicode(filehandle.errorString())
            stream =  QTextStream(filehandle)
            stream.setCodec("UTF-8")
            stream << self.toPlainText()
            self.document().setModified(False)
            RecentFiles().append(self.filename)
        except (IOError, OSError), ioError:
            exception = ioError
コード例 #18
0
def load_stylesheet_pyqt5():
    """
    Loads the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    import vnTrader.qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
コード例 #19
0
ファイル: nfile.py プロジェクト: saminigod/ninja-ide
    def save(self, content, path=None):
        """
        Write a temprorary file with .tnj extension and copy it over the
        original one.
        .nsf = Ninja Swap File
        #FIXME: Where to locate addExtension, does not fit here
        """
        new_path = False
        if path:
            self.attach_to_path(path)
            new_path = True

        save_path = self._file_path

        if not save_path:
            raise NinjaNoFileNameException("I am asked to write a "
                                           "file but no one told me where")
        swap_save_path = "%s.nsp" % save_path

        # If we have a file system watcher, remove the file path
        # from its watch list until we are done making changes.
        if self.__watcher:
            self.__watcher.removePath(save_path)

        flags = QIODevice.WriteOnly | QIODevice.Truncate
        f = QFile(swap_save_path)
        if settings.use_platform_specific_eol():
            flags |= QIODevice.Text

        if not f.open(flags):
            raise NinjaIOException(f.errorString())

        stream = QTextStream(f)
        encoding = get_file_encoding(content)
        if encoding:
            stream.setCodec(encoding)

        encoded_stream = stream.codec().fromUnicode(content)
        f.write(encoded_stream)
        f.flush()
        f.close()
        #SIGNAL: Will save (temp, definitive) to warn folder to do something
        self.emit(SIGNAL("willSave(QString, QString)"),
                  swap_save_path, save_path)
        self.__mtime = os.path.getmtime(swap_save_path)
        shutil.move(swap_save_path, save_path)
        self.reset_state()

        # If we have a file system watcher, add the saved path back
        # to its watch list, otherwise create a watcher and start
        # watching
        if self.__watcher:
            if new_path:
                self.__watcher.removePath(self.__watcher.files()[0])
                self.__watcher.addPath(self._file_path)
            else:
                self.__watcher.addPath(save_path)
        else:
            self.start_watching()
        return self
コード例 #20
0
ファイル: find_in_files.py プロジェクト: manuq/ninja-ide
 def _replace_results(self):
     result = QMessageBox.question(
         self,
         self.tr("Replace Files Contents"),
         self.tr("Are you sure you want to replace the content in "
                 "this files?\n(The change is not reversible)"),
         buttons=QMessageBox.Yes | QMessageBox.No)
     if result == QMessageBox.Yes:
         for index in range(self._result_widget.topLevelItemCount()):
             parent = self._result_widget.topLevelItem(index)
             root_dir_name = parent.dir_name_root
             file_name = parent.text(0)
             file_path = file_manager.create_path(root_dir_name, file_name)
             file_object = QFile(file_path)
             if not file_object.open(QFile.ReadOnly):
                 return
             stream = QTextStream(file_object)
             content = stream.readAll()
             file_object.close()
             pattern = self._find_widget.pattern_line_edit.text()
             case_sensitive = self._find_widget.case_checkbox.isChecked()
             type_ = QRegExp.RegExp if \
                 self._find_widget.type_checkbox.isChecked() else \
                 QRegExp.FixedString
             target = QRegExp(pattern, case_sensitive, type_)
             content.replace(target, self._find_widget.replace_line.text())
             file_manager.store_file_content(file_path, content, False)
コード例 #21
0
ファイル: find_in_files.py プロジェクト: alekibango/ninja-ide
 def _replace_results(self):
     result = QMessageBox.question(self, self.tr("Replace Files Contents"),
         self.tr("Are you sure you want to replace the content in "
                 "this files?\n(The change is not reversible)"),
         buttons=QMessageBox.Yes | QMessageBox.No)
     if result == QMessageBox.Yes:
         for index in xrange(self._result_widget.topLevelItemCount()):
             parent = self._result_widget.topLevelItem(index)
             root_dir_name = unicode(parent.dir_name_root)
             file_name = unicode(parent.text(0))
             file_path = file_manager.create_path(root_dir_name, file_name)
             file_object = QFile(file_path)
             if not file_object.open(QFile.ReadOnly):
                 return
             stream = QTextStream(file_object)
             content = stream.readAll()
             file_object.close()
             pattern = self._find_widget.pattern_line_edit.text()
             case_sensitive = self._find_widget.case_checkbox.isChecked()
             type_ = QRegExp.RegExp if \
                 self._find_widget.type_checkbox.isChecked() else \
                 QRegExp.FixedString
             target = QRegExp(pattern, case_sensitive, type_)
             content.replace(target, self._find_widget.replace_line.text())
             file_manager.store_file_content(file_path, content, False)
コード例 #22
0
ファイル: moviedata.py プロジェクト: hooloong/gitpython
 def exportXml(self, fname):
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='{0}'?>\n"
                    "<!DOCTYPE MOVIES>\n"
                    "<MOVIES VERSION='1.0'>\n".format(CODEC))
         for key, movie in self.__movies:
             stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' "
                        "ACQUIRED='{2}'>\n".format(movie.year,
                        movie.minutes,
                        movie.acquired.toString(Qt.ISODate))) \
                    << "<TITLE>" << Qt.escape(movie.title) \
                    << "</TITLE>\n<NOTES>"
             if not movie.notes.isEmpty():
                 stream << "\n" << Qt.escape(
                         encodedNewlines(movie.notes))
             stream << "\n</NOTES>\n</MOVIE>\n"
         stream << "</MOVIES>\n"
     except EnvironmentError as e:
         error = "Failed to export: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Exported {0} movie records to {1}".format(
                 len(self.__movies),
                 QFileInfo(fname).fileName())
コード例 #23
0
ファイル: QSingleton.py プロジェクト: usbceic/ceic-sv
    def __init__(self, appID, argv):
        #--------------------------------------------------------------------------------------------------------------
        # INICIAR LA CLASE
        #--------------------------------------------------------------------------------------------------------------
        super(QSingleton, self).__init__(argv)

        #--------------------------------------------------------------------------------------------------------------
        # CONFIGURACIONES INICIALES
        #--------------------------------------------------------------------------------------------------------------

        self.appID = appID
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self.appID)
        self._isRunning = self._outSocket.waitForConnected()

        # Si hay instancias previas corriendo
        if self._isRunning:
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')

        # Si es la primera instancia
        else:
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self.appID)
            self._server.newConnection.connect(self._onNewConnection)
コード例 #24
0
ファイル: moviedata.py プロジェクト: hooloong/gitpython
 def saveQTextStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         for key, movie in self.__movies:
             stream << "{{MOVIE}} " << movie.title << "\n" \
                    << movie.year << " " << movie.minutes << " " \
                    << movie.acquired.toString(Qt.ISODate) \
                    << "\n{NOTES}"
             if not movie.notes.isEmpty():
                 stream << "\n" << movie.notes
             stream << "\n{{ENDMOVIE}}\n"
     except EnvironmentError as e:
         error = "Failed to save: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {0} movie records to {1}".format(
                 len(self.__movies),
                 QFileInfo(self.__fname).fileName())
コード例 #25
0
 def exportXml(self, fname):
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='{0}'?>\n"
                    "<!DOCTYPE MOVIES>\n"
                    "<MOVIES VERSION='1.0'>\n".format(CODEC))
         for key, movie in self.__movies:
             stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' "
                        "ACQUIRED='{2}'>\n".format(movie.year,
                        movie.minutes,
                        movie.acquired.toString(Qt.ISODate))) \
                    << "<TITLE>" << Qt.escape(movie.title) \
                    << "</TITLE>\n<NOTES>"
             if not movie.notes.isEmpty():
                 stream << "\n" << Qt.escape(encodedNewlines(movie.notes))
             stream << "\n</NOTES>\n</MOVIE>\n"
         stream << "</MOVIES>\n"
     except EnvironmentError as e:
         error = "Failed to export: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Exported {0} movie records to {1}".format(
             len(self.__movies),
             QFileInfo(fname).fileName())
コード例 #26
0
 def saveQTextStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         for key, movie in self.__movies:
             stream << "{{MOVIE}} " << movie.title << "\n" \
                    << movie.year << " " << movie.minutes << " " \
                    << movie.acquired.toString(Qt.ISODate) \
                    << "\n{NOTES}"
             if not movie.notes.isEmpty():
                 stream << "\n" << movie.notes
             stream << "\n{{ENDMOVIE}}\n"
     except EnvironmentError as e:
         error = "Failed to save: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {0} movie records to {1}".format(
             len(self.__movies),
             QFileInfo(self.__fname).fileName())
コード例 #27
0
ファイル: __init__.py プロジェクト: cbodes/ECEIR-Swipe-System
def load_stylesheet_pyqt5():
    """
    Loads the stylesheet for use in a pyqt5 application.
    :return the stylesheet string
    """
    # Validate that rc files is updated
    compile_qrc.compile_all()

    # Smart import of the rc file
    import qdarkgraystyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(':qdarkgraystyle/style.qss')
    if not f.exists():
        _logger().error('Unable to load stylesheet, file not found in '
                        'resources')
        return ''
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
コード例 #28
0
def main(argv):
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(QPixmap(":/logo_small")))
    app.setOrganizationName('Hardcoded Software')
    app.setApplicationName('moneyGuru')
    settings = QSettings()
    LOGGING_LEVEL = logging.DEBUG if adjust_after_deserialization(settings.value('DebugMode')) else logging.WARNING
    setupQtLogging(level=LOGGING_LEVEL)
    logging.debug('started in debug mode')
    if ISLINUX:
        stylesheetFile = QFile(':/stylesheet_lnx')
    else:
        stylesheetFile = QFile(':/stylesheet_win')
    stylesheetFile.open(QFile.ReadOnly)
    textStream = QTextStream(stylesheetFile)
    style = textStream.readAll()
    stylesheetFile.close()
    app.setStyleSheet(style)
    lang = settings.value('Language')
    locale_folder = op.join(BASE_PATH, 'locale')
    hscommon.trans.install_gettext_trans_under_qt(locale_folder, lang)
    # Many strings are translated at import time, so this is why we only import after the translator
    # has been installed
    from qt.app import MoneyGuru
    app.setApplicationVersion(MoneyGuru.VERSION)
    mgapp =  MoneyGuru()
    install_excepthook()
    exec_result = app.exec_()
    del mgapp
    # Since PyQt 4.7.2, I had crashes on exit, and from reading the mailing list, it seems to be
    # caused by some weird crap about C++ instance being deleted with python instance still living.
    # The worst part is that Phil seems to say this is expected behavior. So, whatever, this
    # gc.collect() below is required to avoid a crash.
    gc.collect()
    return exec_result
コード例 #29
0
 def readyRead(self):       #  可以读数据了
     local = self.sender()  #  取得是哪个localsocket可以读数据了
     if (local == None):
         return
     _in = QTextStream(local)
     readMsg = _in.readAll()
     print "recv Msg:",readMsg
     self.emit(SIGNAL("newMessage(QString)"), QString(readMsg))
コード例 #30
0
 def readyRead(self):  #  可以读数据了
     local = self.sender()  #  取得是哪个localsocket可以读数据了
     if (local == None):
         return
     _in = QTextStream(local)
     readMsg = _in.readAll()
     print "recv Msg:", readMsg
     self.emit(SIGNAL("newMessage(QString)"), QString(readMsg))
コード例 #31
0
  def __init__(self, iface):
    """Constructor for the dialog.

    Args:
      iface: QgsInterface instance.
    """
    QDialog.__init__(self, iface.mainWindow())
    self.setupUi(self)

    # Settings Tab
    # Show the current value of client_id and client_secret
    client_id = settings.read('gmeconnector/CLIENT_ID')
    client_secret = settings.read('gmeconnector/CLIENT_SECRET')
    if client_id is None:
      client_id = ''
    if client_secret is None:
      client_secret = ''
    self.lineEdit1.setText(client_id)
    self.lineEdit2.setText(client_secret)

    # Other settings
    self.comboBoxProjects.setEnabled(False)
    self.checkBoxDefault.stateChanged.connect(self.comboBoxProjects.setEnabled)
    self.comboBoxFormat.addItem('JPEG', 'image/jpeg')
    self.comboBoxFormat.addItem('PNG', 'image/png')
    defaultFormat = settings.read('gmeconnector/WMS_IMAGE_FORMAT')

    if defaultFormat:
      defaultIndex = self.comboBoxFormat.findText(defaultFormat)
      if defaultIndex != -1:
        self.comboBoxFormat.setCurrentIndex(defaultIndex)
    self.comboBoxFormat.currentIndexChanged.connect(self.handleFormatChanged)

    # OAuth help
    oAuthPage = QWebPage()
    oAuthPage.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
    self.webViewOAuth.setPage(oAuthPage)

    # Load the oauth_help file
    helpFile = QFile(':/plugins/googlemapsengineconnector/oauth_help.html')
    helpFile.open(QIODevice.ReadOnly | QIODevice.Text)
    helpStr = QTextStream(helpFile)
    helpText = helpStr.readAll()
    self.webViewOAuth.setHtml(helpText)
    self.webViewOAuth.linkClicked.connect(self.handleWebLink)

    # About Tab
    aboutPage = QWebPage()
    aboutPage.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
    self.webViewAbout.setPage(aboutPage)
    # Load the about.html file and add current version info.
    aboutFile = QFile(':/plugins/googlemapsengineconnector/about.html')
    aboutFile.open(QIODevice.ReadOnly | QIODevice.Text)
    aboutStr = QTextStream(aboutFile)
    aboutText = aboutStr.readAll()
    newText = aboutText.format(version='1.0')
    self.webViewAbout.setHtml(newText)
    self.webViewAbout.linkClicked.connect(self.handleWebLink)
コード例 #32
0
ファイル: QSingleton.py プロジェクト: usbceic/ceic-sv
 def _onNewConnection(self):
     if self._inSocket:
         self._inSocket.readyRead.disconnect(self._onReadyRead)
     self._inSocket = self._server.nextPendingConnection()
     if not self._inSocket:
         return
     self._inStream = QTextStream(self._inSocket)
     self._inStream.setCodec('UTF-8')
     self._inSocket.readyRead.connect(self._onReadyRead)
コード例 #33
0
def read_network_path():
    """get the netowrk config file location"""
    network_config = QFile(os.path.join(USER_PLUGIN_DIR, 'network_path.txt'))

    if network_config.open(QIODevice.ReadOnly):
        stream = QTextStream(network_config)
        f_path = stream.readLine()
        if f_path:
            return f_path
コード例 #34
0
ファイル: pg_utils.py プロジェクト: cb-flts/stdm
def table_view_dependencies(table_name, column_name=None):
    """
    Find database views that are dependent on the given table and
    optionally the column.
    :param table_name: Table name
    :type table_name: str
    :param column_name: Name of the column whose dependent views are to be
    extracted.
    :type column_name: str
    :return: A list of views which are dependent on the given table name and
    column respectively.
    :rtype: list(str)
    """
    views = []

    # Load the SQL file depending on whether its table or table/column
    if column_name is None:
        script_path = PLUGIN_DIR + '/scripts/table_related_views.sql'
    else:
        script_path = PLUGIN_DIR + '/scripts/table_column_related_views.sql'

    script_file = QFile(script_path)

    if not script_file.exists():
        raise IOError('SQL file for retrieving view dependencies could '
                      'not be found.')

    else:
        if not script_file.open(QIODevice.ReadOnly):
            raise IOError('Failed to read the SQL file for retrieving view '
                          'dependencies.')

        reader = QTextStream(script_file)
        sql = reader.readAll()
        if sql:
            t = text(sql)
            if column_name is None:
                result = _execute(
                    t,
                    table_name=table_name
                )

            else:
                result = _execute(
                    t,
                    table_name=table_name,
                    column_name=column_name
                )

            # Get view names
            for r in result:
                view_name = r['view_name']
                views.append(view_name)

    return views
コード例 #35
0
ファイル: logs.py プロジェクト: ViktorNova/Cadence
    def __init__(self, parent):
        QThread.__init__(self, parent)

        self.fCloseNow   = False
        self.fPurgeLogs  = False
        self.fRealParent = parent

        # -------------------------------------------------------------
        # Take some values from Logs Window

        self.LOG_FILE_JACK   = LogsW.LOG_FILE_JACK
        self.LOG_FILE_A2J    = LogsW.LOG_FILE_A2J
        self.LOG_FILE_LASH   = LogsW.LOG_FILE_LASH
        self.LOG_FILE_LADISH = LogsW.LOG_FILE_LADISH

        # -------------------------------------------------------------
        # Init logs

        if self.LOG_FILE_JACK is not None:
            self.fLogFileJACK = QFile(self.LOG_FILE_JACK)
            self.fLogFileJACK.open(QIODevice.ReadOnly)
            self.fLogStreamJACK = QTextStream(self.fLogFileJACK)
            self.fLogStreamJACK.setCodec("UTF-8")

            if self.fLogFileJACK.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamJACK.seek(self.fLogFileJACK.size() - self.MAX_INITIAL_SIZE)

        if self.LOG_FILE_A2J is not None:
            self.fLogFileA2J = QFile(self.LOG_FILE_A2J)
            self.fLogFileA2J.open(QIODevice.ReadOnly)
            self.fLogStreamA2J = QTextStream(self.fLogFileA2J)
            self.fLogStreamA2J.setCodec("UTF-8")

            if self.fLogFileA2J.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamA2J.seek(self.fLogFileA2J.size() - self.MAX_INITIAL_SIZE)

        if self.LOG_FILE_LASH is not None:
            self.fLogFileLASH = QFile(self.LOG_FILE_LASH)
            self.fLogFileLASH.open(QIODevice.ReadOnly)
            self.fLogStreamLASH = QTextStream(self.fLogFileLASH)
            self.fLogStreamLASH.setCodec("UTF-8")

            if self.fLogFileLASH.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamLASH.seek(self.fLogFileLASH.size() - self.MAX_INITIAL_SIZE)

        if self.LOG_FILE_LADISH is not None:
            self.fLogFileLADISH = QFile(self.LOG_FILE_LADISH)
            self.fLogFileLADISH.open(QIODevice.ReadOnly)
            self.fLogStreamLADISH = QTextStream(self.fLogFileLADISH)
            self.fLogStreamLADISH.setCodec("UTF-8")

            if self.fLogFileLADISH.size() > self.MAX_INITIAL_SIZE:
                self.fLogStreamLADISH.seek(self.fLogFileLADISH.size() - self.MAX_INITIAL_SIZE)
コード例 #36
0
ファイル: pyqt5_loader.py プロジェクト: xiaorui531/easylearn
def load_stylesheet_pyqt5(**kwargs):
    """
    Loads the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file

    if kwargs["style"] == "style_Dark":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_Dark_rc
    if kwargs["style"] == "style_DarkOrange":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_DarkOrange_rc
    if kwargs["style"] == "style_Classic":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_Classic_rc

    if kwargs["style"] == "style_navy":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_navy_rc

    if kwargs["style"] == "style_gray":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_gray_rc

    if kwargs["style"] == "style_blue":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_blue_rc

    if kwargs["style"] == "style_black":
        import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_black_rc
    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":PyQt5_stylesheets/%s.qss" % kwargs["style"])
    if not f.exists():
        f = QFile(":PyQt5_stylesheets/%s.css" % kwargs["style"])
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
コード例 #37
0
ファイル: globalt.py プロジェクト: IZSVenezie/VetEpiGIS-Stat
 def save(self):
     fileName = QFileDialog.getSaveFileName(self, caption='Save As...')
     try:
         file = QFile(fileName + '.txt')
         file.open( QIODevice.WriteOnly | QIODevice.Text )
         out = QTextStream(file)
         out << self.plainTextEdit.toPlainText()
         out.flush()
         file.close()
         self.close()
         return True
     except IOError:
         return False
コード例 #38
0
ファイル: textedit.py プロジェクト: abers/learn
 def load(self):
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError, unicode(fh.errorString())
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         self.setPlainText(stream.readAll())
         self.document().setModified(False)
     except (IOError, OSError), e:
         exception = e
コード例 #39
0
ファイル: exp2BUGS.py プロジェクト: solymosin/maps2winbugs
 def save(self):
     fileName = QFileDialog.getSaveFileName(self, caption='Save As...')
     try:
         file = QFile(fileName + '.txt')
         file.open(QIODevice.WriteOnly | QIODevice.Text)
         out = QTextStream(file)
         out << self.plainTextEdit.toPlainText()
         out.flush()
         file.close()
         self.close()
         return True
     except IOError:
         return False
コード例 #40
0
ファイル: textedit.py プロジェクト: dpeinado/restec
 def load(self):
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError, unicode(fh.errorString())
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         self.setPlainText(stream.readAll())
         self.document().setModified(False)
     except (IOError, OSError), e:
         exception = e
コード例 #41
0
def main():
    print_process_id()

    app = QtGui.QApplication([])
    #app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt())

    file = QFile(os.path.join(CURR_DIRECTORY, "qdarkstyle.qss"))
    file.open(QFile.ReadOnly | QFile.Text)
    stream = QTextStream(file)
    app.setStyleSheet(stream.readAll())

    widget = ExampleWidget()

    widget.show()

    app.exec_()
コード例 #42
0
    def __init__(self, id, *argv):

        super(QtSingleApplication, self).__init__(*argv)
        self._id = id
        self._activationWindow = None
        self._activateOnMessage = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            # No, there isn't.
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)
コード例 #43
0
def write_file(filename, content):
    _file = QFile(filename)
    if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate):
        raise EdisIOError
    outfile = QTextStream(_file)
    outfile << content
    return filename
コード例 #44
0
 def saveCompleteHtml(self, htmlFile):
     html = QFile(htmlFile)
     html.open(QIODevice.WriteOnly)
     savestream = QTextStream(html)
     css = QFile(self.settings.cssfile)
     css.open(QIODevice.ReadOnly)
     # Use a html lib may be a better idea?
     savestream << "<html><head><meta charset='utf-8'></head>"
     # Css is inlined.
     savestream << "<style>"
     savestream << QTextStream(css).readAll()
     savestream << "</style>"
     # Note content
     savestream << self.toHtml()
     savestream << "</html>"
     html.close()
コード例 #45
0
ファイル: georeferencer.py プロジェクト: lhow-atr/ArkSpatial
 def writeGcpFile(gc, path):
     outFile = QFile(path)
     if (not outFile.open(QIODevice.WriteOnly | QIODevice.Text)):
         return 'Unable to open GCP file for writing'
     outStream = QTextStream(outFile)
     outStream << gc.asCsv()
     outFile.close()
コード例 #46
0
    def acceptConnection(self):
        self.tcpServerConnection = self.tcpServer.nextPendingConnection()
        self.tcpServerConnection.readyRead.connect(self.updateLog)
        self.tcpServerConnection.error.connect(self.displayError)

        self.file = QFile(self.filename)
        if not self.file.open(QFile.Append):
            QMessageBox.warning(
                self, self.title, "Unable to write file {}:\n{}.".format(
                    self.filename, self.file.errorString()))
            self.file = None
            return
        self.textStream = QTextStream(self.file)
        self.textStream.setCodec('UTF-8')

        self.serverStatusLabel.setText("Logging ...")
        self.tcpServer.close()
コード例 #47
0
ファイル: __init__.py プロジェクト: pratikone/videoVenom
def get_style(style_sheet):
    try:
        mod = importlib.import_module("." + style_sheet, __name__)
        hasattr(mod, "qt_resource_name")
        f = QFile(":/%s/style.qss" % style_sheet)                                
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()    
    except ImportError as e:
        print "Style sheet not available. Use available_styles() to check for valid styles"
        return u""
    except Exception as e:
        print "Style sheet available, but an error occured..."
        traceback.print_exc()
        return u""
        
    return stylesheet
コード例 #48
0
	def __init__(self, species=None, parent=None):
		super(CharacterSheetDocument, self).__init__( parent)

		self.__species = species

		## Lade Datei mit Stylesheet-Informationen
		cssFile = QFile(":stylesheets/sheet.css")
		if not cssFile.open(QIODevice.ReadOnly):
			raise ErrFileNotOpened( "Wile opening file \"{}\", the error \"{}\" occured.".format(
				item,
				cssFile.errorString()
			), filename=item )
		cssStream = QTextStream(cssFile)
		cssContent = cssStream.readAll()
		cssFile.close()

		self.setDefaultStyleSheet(cssContent)
コード例 #49
0
    def __init__(self, species=None, parent=None):
        super(CharacterSheetDocument, self).__init__(parent)

        self.__species = species

        ## Lade Datei mit Stylesheet-Informationen
        cssFile = QFile(":stylesheets/sheet.css")
        if not cssFile.open(QIODevice.ReadOnly):
            raise ErrFileNotOpened(
                "Wile opening file \"{}\", the error \"{}\" occured.".format(
                    item, cssFile.errorString()),
                filename=item)
        cssStream = QTextStream(cssFile)
        cssContent = cssStream.readAll()
        cssFile.close()

        self.setDefaultStyleSheet(cssContent)
コード例 #50
0
def get_style(style_sheet):
    try:
        mod = importlib.import_module("." + style_sheet, __name__)
        hasattr(mod, "qt_resource_name")
        f = QFile(":/%s/style.qss" % style_sheet)
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
    except ImportError as e:
        print "Style sheet not available. Use available_styles() to check for valid styles"
        return u""
    except Exception as e:
        print "Style sheet available, but an error occured..."
        traceback.print_exc()
        return u""

    return stylesheet
コード例 #51
0
def load_stylesheet(pyside=True):
    """
    Load the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet() will not receive pyside parameter in version 3. "
        "Set QtPy environment variable to specify the Qt binding insteady.",
        FutureWarning
    )
    # Smart import of the rc file
    if pyside:
        import qdarkstyle.pyside_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
コード例 #52
0
    def save(self, content, path=None):
        """
        Write a temprorary file with .tnj extension and copy it over the
        original one.
        .nsf = Ninja Swap File
        #FIXME: Where to locate addExtension, does not fit here
        """
        if path and self._file_path:
            created_file = NFile(path).save(content)
            self.emit(SIGNAL("savedAsNewFile(PyQt_PyObject, QString, QString)"),
                        created_file, self._file_path, path)
            return created_file
        elif path and not self._file_path:
            self.attach_to_path(path)

        save_path = self._file_path

        if not save_path:
            raise NinjaNoFileNameException("I am asked to write a "
                                "file but no one told me where")
        swap_save_path = u"%s.nsp" % save_path

        flags = QIODevice.WriteOnly | QIODevice.Truncate
        f = QFile(swap_save_path)
        if settings.use_platform_specific_eol():
            flags |= QIODevice.Text

        if not f.open(flags):
            raise NinjaIOException(f.errorString())

        stream = QTextStream(f)
        encoding = get_file_encoding(content)
        if encoding:
            stream.setCodec(encoding)

        encoded_stream = stream.codec().fromUnicode(content)
        f.write(encoded_stream)
        f.flush()
        f.close()
        #SIGNAL: Will save (temp, definitive) to warn folder to do something
        self.emit(SIGNAL("willSave(QString, QString)"), swap_save_path,
                                                        save_path)
        shutil.move(swap_save_path, save_path)
        self.reset_state()
        return self
コード例 #53
0
ファイル: nfile.py プロジェクト: pdorrell/ninja-ide
    def save(self, content, path=None):
        """
        Write a temprorary file with .tnj extension and copy it over the
        original one.
        .nsf = Ninja Swap File
        #FIXME: Where to locate addExtension, does not fit here
        """
        if path and self._file_path:
            created_file = NFile(path).save(content)
            self.emit(SIGNAL("savedAsNewFile(PyQt_PyObject, QString, QString)"),
                        created_file, self._file_path, path)
            return created_file
        elif path and not self._file_path:
            self.attach_to_path(path)

        save_path = self._file_path

        if not save_path:
            raise NinjaNoFileNameException("I am asked to write a "
                                "file but no one told me where")
        swap_save_path = u"%s.nsp" % save_path

        flags = QIODevice.WriteOnly | QIODevice.Truncate
        f = QFile(swap_save_path)
        if settings.use_platform_specific_eol():
            flags |= QIODevice.Text

        if not f.open(flags):
            raise NinjaIOException(f.errorString())

        stream = QTextStream(f)
        encoding = get_file_encoding(content)
        if encoding:
            stream.setCodec(encoding)

        encoded_stream = stream.codec().fromUnicode(content)
        f.write(encoded_stream)
        f.flush()
        f.close()
        #SIGNAL: Will save (temp, definitive) to warn folder to do something
        self.emit(SIGNAL("willSave(QString, QString)"), swap_save_path,
                                                        save_path)
        shutil.move(swap_save_path, save_path)
        self.reset_state()
        return self
コード例 #54
0
ファイル: textedit.py プロジェクト: hooloong/gitpython
 def load(self):
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         self.setPlainText(stream.readAll())
         self.document().setModified(False)
     except EnvironmentError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
コード例 #55
0
ファイル: pg_utils.py プロジェクト: olivierdalang/stdm
def foreign_key_parent_tables(table_name):
    """
    Functions that searches for foreign key references in the specified table.
    :param table_name: Name of the database table.
    :type table_name: str
    :return: A list of tuples containing the local column name, foreign table
    name and corresponding foreign column name.
    :rtype: list
    """
    #Check if the view for listing foreign key references exists
    fk_ref_view = pg_table_exists("foreign_key_references")

    #Create if it does not exist
    if not fk_ref_view:
        script_path = PLUGIN_DIR + "/scripts/foreign_key_references.sql"

        script_file = QFile(script_path)
        if script_file.exists():
            if not script_file.open(QIODevice.ReadOnly):
                return None

            reader = QTextStream(script_file)
            sql = reader.readAll()
            if sql:
                t = text(sql)
                _execute(t)

        else:
            return None

    #Fetch foreign key references
    sql = "SELECT column_name,foreign_table_name,foreign_column_name FROM " \
          "foreign_key_references where table_name=:tb_name"
    t = text(sql)
    result = _execute(t, tb_name=table_name)

    fk_refs = []

    for r in result:
        fk_ref = r["column_name"], r["foreign_table_name"],\
                 r["foreign_column_name"]
        fk_refs.append(fk_ref)

    return fk_refs
コード例 #56
0
ファイル: pqHelp.py プロジェクト: tallforasmurf/PPQT
    def __init__(self, parent=None ):
        super(helpDisplay, self).__init__(parent)
        # make page unmodifiable
        self.page().setContentEditable(False)
        # initialize settings
        # Find out the nearest font to Palatino
        qf = QFont()
        qf.setStyleStrategy(QFont.PreferAntialias+QFont.PreferMatch)
        qf.setStyleHint(QFont.Serif)
        qf.setFamily(QString(u'Palatino'))
        qfi = QFontInfo(qf)
        # set the default font to that serif font
        self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family())
        self.settings().setFontSize(QWebSettings.DefaultFontSize, 16)
        self.settings().setFontSize(QWebSettings.MinimumFontSize, 6)
        self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
        self.textZoomFactor = 1.0
        self.setTextSizeMultiplier(self.textZoomFactor)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, False)
        self.settings().setAttribute(QWebSettings.JavaEnabled, False)
        self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
        self.settings().setAttribute(QWebSettings.ZoomTextOnly, True)
        #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
        self.userFindText = QString()
        # Look for pqHelp.html in the app folder and copy its text into
        # a local buffer. If it isn't found, put a message there instead.
        # We need to keep it in order to implement the "back" function.
        helpPath = os.path.join(IMC.appBasePath,u'pqHelp.html')
        helpFile = QFile(helpPath)
        if not helpFile.exists():
            self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p>
	    <p>Looking in {0}'''.format(helpPath)
                                )
        elif not helpFile.open(QIODevice.ReadOnly) :
            self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p>
	    <p>Looking in {0}</p><p>Error code {1}</p>'''.format(helpPath,
                                                                 helpFile.error())
                                                         )
        else:
            helpStream = QTextStream(helpFile)
            helpStream.setCodec('ISO8859-1')
            self.HTMLstring = helpStream.readAll()
        self.setHtml(self.HTMLstring)
コード例 #57
0
 def __init__(self, parent=None):
     """ Инициализируем интерфейс и задаём начальные значения внутренних переменных """
     QMainWindow.__init__(self, parent)
     self._alreadyShown = False
     self.setupUi()
     self._feedName = 'feed/http://habrahabr.ru/rss/'
     self._filters = { 'Все' : '.*' }
     self._categorizer = self.categorizeByDate
     file = QFile(':/templates/content.html')
     if file.open(QIODevice.ReadOnly | QIODevice.Text):
         s = QTextStream(file)
         self._entryTemplate = Template(s.readAll())
     else:
         self._entryTemplate = Template('')
     self._curCategory = None
     self._curEntryId = -1
     self._loadingData = False
     self._reader = libgreader.GoogleReader(None)
     self._loggedIn = False
コード例 #58
0
ファイル: __init__.py プロジェクト: petfactory/PySide
def load_stylesheet(pyside=True):
    """
    Loads the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    # Smart import of the rc file
    if pyside:
        #import qdarkstyle.pyside_style_rc
        import petfactoryStyle.pyside_style_rc
    else:
        import petfactoryStyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    #f = QFile(":qdarkstyle/style.qss")
    f = QFile(":petfactoryStyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #353434;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet