Пример #1
0
    def readXmlDocument(self):
        xml_file = QFile(':/xml/examples.xml')
        xml_file.open(QFile.ReadOnly | QFile.Text)
        contents = xml_file.readAll().data()
        xml_file.close()

        self.contentsDoc = parseString(contents)
Пример #2
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 theme.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;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet
Пример #3
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.setupUi(self)

        headers = ("Title", "Description")

        file = QFile(':/default.txt')
        file.open(QIODevice.ReadOnly)
        model = TreeModel(headers, file.readAll())
        file.close()

        self.view.setModel(model)
        for column in range(model.columnCount()):
            self.view.resizeColumnToContents(column)

        self.exitAction.triggered.connect(QApplication.instance().quit)

        self.view.selectionModel().selectionChanged.connect(self.updateActions)

        self.actionsMenu.aboutToShow.connect(self.updateActions)
        self.insertRowAction.triggered.connect(self.insertRow)
        self.insertColumnAction.triggered.connect(self.insertColumn)
        self.removeRowAction.triggered.connect(self.removeRow)
        self.removeColumnAction.triggered.connect(self.removeColumn)
        self.insertChildAction.triggered.connect(self.insertChild)

        self.updateActions()
Пример #4
0
 def read(self, fileNameOrDevice):
     """
     Public method to read a login data file.
     
     @param fileNameOrDevice name of the file to read (string)
         or reference to the device to read (QIODevice)
     @return tuple containing the logins, forms and never URLs
     """
     self.__logins = {}
     self.__loginForms = {}
     self.__never = []
     
     if isinstance(fileNameOrDevice, QIODevice):
         self.setDevice(fileNameOrDevice)
     else:
         f = QFile(fileNameOrDevice)
         if not f.exists():
             return self.__logins, self.__loginForms, self.__never
         f.open(QFile.ReadOnly)
         self.setDevice(f)
     
     while not self.atEnd():
         self.readNext()
         if self.isStartElement():
             version = self.attributes().value("version")
             if self.name() == "Password" and \
                (not version or version == "1.0"):
                 self.__readPasswords()
             else:
                 self.raiseError(QCoreApplication.translate(
                     "PasswordReader",
                     "The file is not a Passwords version 1.0 file."))
     
     return self.__logins, self.__loginForms, self.__never
Пример #5
0
 def read(self, fileNameOrDevice):
     """
     Public method to read an XBEL bookmark file.
     
     @param fileNameOrDevice name of the file to read (string)
         or reference to the device to read (QIODevice)
     @return reference to the root node (BookmarkNode)
     """
     if isinstance(fileNameOrDevice, QIODevice):
         self.setDevice(fileNameOrDevice)
     else:
         f = QFile(fileNameOrDevice)
         if not f.exists():
             return BookmarkNode(BookmarkNode.Root)
         f.open(QFile.ReadOnly)
         self.setDevice(f)
     
     root = BookmarkNode(BookmarkNode.Root)
     while not self.atEnd():
         self.readNext()
         if self.isStartElement():
             version = self.attributes().value("version")
             if self.name() == "xbel" and \
                (not version or version == "1.0"):
                 self.__readXBEL(root)
             else:
                 self.raiseError(QCoreApplication.translate(
                     "XbelReader",
                     "The file is not an XBEL version 1.0 file."))
     
     return root
Пример #6
0
def set_window_style(window):
    """
    :return the stylesheet string
    """
    # Smart import of the rc file

    f = QFile(":dark_style.qss")
    if not f.exists():
        print('Custom stylesheet not present')
        Lumberjack.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
        window.setWindowIcon(QIcon(':/app_icons/rc/PAT_icon.png'))
        window.setStyleSheet(stylesheet)
Пример #7
0
def load(path):
    file = QFile(path)
    try:
        file.open(QIODevice.ReadOnly)
        return file.readAll()
    finally:
        file.close()
Пример #8
0
    def _on_browser_open(self):
        if self._imagecontainer is None:
            QMessageBox.warning(self, 'Data structure not loaded',
                                'The input directory structure file was not loaded.\n'
                                'Click "Scan input directory" in section "General" to proceed.')
        elif self._browser is None:
            try:
                browser = Browser(self._settings, self._imagecontainer, None)
                browser.show()
                browser.raise_()
                browser.setFocus()
                app = AppPreferences()

                f = QFile(":cecog_style")
                f.open(QFile.ReadOnly|QFile.Text)
                ts = QTextStream(f).readAll()

                browser.setStyleSheet(ts)
                self._browser = browser
            except Exception as e:
                traceback.print_exc()
                QMessageBox.critical(self, "Error", str(e))
        else:
            self._browser.show()
            self._browser.raise_()
Пример #9
0
    def readTextFromFile(self, fileName=None, encoding=None):
        previousFileName = self._fileName
        if fileName:
            self._fileName = fileName

            # Only try to detect encoding if it is not specified
        if encoding is None and globalSettings.detectEncoding:
            encoding = self.detectFileEncoding(self._fileName)

            # TODO: why do we open the file twice: for detecting encoding
            # and for actual read? Can we open it just once?
        openfile = QFile(self._fileName)
        openfile.open(QFile.ReadOnly)
        stream = QTextStream(openfile)
        encoding = encoding or globalSettings.defaultCodec
        if encoding:
            stream.setCodec(encoding)
            # If encoding is specified or detected, we should save the file with
            # the same encoding
            self.editBox.document().setProperty("encoding", encoding)

        text = stream.readAll()
        openfile.close()

        self.editBox.setPlainText(text)
        self.editBox.document().setModified(False)

        if previousFileName != self._fileName:
            self.updateActiveMarkupClass()
            self.fileNameChanged.emit()
Пример #10
0
    def __init__(self, parent=None):
        super(DragWidget, self).__init__(parent)

        dictionaryFile = QFile(':/dictionary/words.txt')
        dictionaryFile.open(QIODevice.ReadOnly)

        x = 5
        y = 5

        for word in QTextStream(dictionaryFile).readAll().split():
            wordLabel = DragLabel(word, self)
            wordLabel.move(x, y)
            wordLabel.show()
            x += wordLabel.width() + 2
            if x >= 195:
                x = 5
                y += wordLabel.height() + 2

        newPalette = self.palette()
        newPalette.setColor(QPalette.Window, Qt.white)
        self.setPalette(newPalette)

        self.setAcceptDrops(True)
        self.setMinimumSize(400, max(200, y))
        self.setWindowTitle("Draggable Text")
Пример #11
0
 def loadStyleSheet(self, sheetName):
     file_name = sheetName + '.css'
     file = QFile('../css/{}'.format(file_name))
     file.open(QFile.ReadOnly)
     styleSheet = file.readAll()
     styleSheet = str(styleSheet, encoding='utf8')
     QtWidgets.QApplication.instance().setStyleSheet(styleSheet)
Пример #12
0
 def read(self, fileNameOrDevice):
     """
     Public method to read a user agent file.
     
     @param fileNameOrDevice name of the file to read (string)
         or reference to the device to read (QIODevice)
     @return dictionary with user agent data (host as key, agent string as
         value)
     """
     self.__agents = {}
     
     if isinstance(fileNameOrDevice, QIODevice):
         self.setDevice(fileNameOrDevice)
     else:
         f = QFile(fileNameOrDevice)
         if not f.exists():
             return self.__agents
         f.open(QFile.ReadOnly)
         self.setDevice(f)
     
     while not self.atEnd():
         self.readNext()
         if self.isStartElement():
             version = self.attributes().value("version")
             if self.name() == "UserAgents" and \
                (not version or version == "1.0"):
                 self.__readUserAgents()
             else:
                 self.raiseError(QCoreApplication.translate(
                     "UserAgentReader",
                     "The file is not a UserAgents version 1.0 file."))
     
     return self.__agents
Пример #13
0
 def set_StyleSheet(self, sheetName):
     if sheetName:
         file = QFile('stylesheet/%s.qss' % sheetName.lower())
         file.open(QFile.ReadOnly)
         styleSheet = file.readAll()
         styleSheet = str(styleSheet, encoding='utf8') # Python v3.
         self.setStyleSheet(styleSheet)
Пример #14
0
    def __init__(self, parent=None):
        super(SourceWidget, self).__init__(parent)

        self.mimeData = None

        imageFile = QFile(':/images/example.svg')
        imageFile.open(QIODevice.ReadOnly)
        self.imageData = imageFile.readAll()
        imageFile.close()

        imageArea = QScrollArea()
        self.imageLabel = QSvgWidget()
        self.imageLabel.renderer().load(self.imageData)
        imageArea.setWidget(self.imageLabel)

        instructTopLabel = QLabel("This is an SVG drawing:")
        instructBottomLabel = QLabel("Drag the icon to copy the drawing as a PNG file:")
        dragIcon = QPushButton("Export")
        dragIcon.setIcon(QIcon(':/images/drag.png'))
        dragIcon.pressed.connect(self.startDrag)

        layout = QGridLayout()
        layout.addWidget(instructTopLabel, 0, 0, 1, 2)
        layout.addWidget(imageArea, 1, 0, 2, 2)
        layout.addWidget(instructBottomLabel, 3, 0)
        layout.addWidget(dragIcon, 3, 1)
        self.setLayout(layout)
        self.setWindowTitle("Delayed Encoding")
Пример #15
0
    def __init__(self, ui_file, bus, devices=[], parent=None):
        QtWidgets.QMainWindow.__init__(self, parent=parent)

        self.bus = bus

        # TODO: CAMPid 980567566238416124867857834291346779
        ico_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), "icon.ico")
        ico = QtGui.QIcon(ico_file)
        self.setWindowIcon(ico)

        ui = ui_file
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ui.action_About.triggered.connect(self.about)

        device_tree = epyqlib.devicetree.Tree()
        device_tree_model = epyqlib.devicetree.Model(root=device_tree)
        device_tree_model.device_removed.connect(self._remove_device)
        self.ui.device_tree.setModel(device_tree_model)

        self.ui.device_tree.device_selected.connect(self.set_current_device)
Пример #16
0
	def updateStyleSheet(self):
		if globalSettings.styleSheet:
			sheetfile = QFile(globalSettings.styleSheet)
			sheetfile.open(QIODevice.ReadOnly)
			self.ss = QTextStream(sheetfile).readAll()
			sheetfile.close()
		else:
			self.ss = ''
Пример #17
0
 def load_style_sheet(self, sheetName, iconsDir):
     """load qss file"""
     print('Using qss file: %s'%sheetName)
     qss = QFile(sheetName)
     qss.open(QFile.ReadOnly)
     styleSheet = str(qss.readAll(), encoding='utf8').replace(':PathPrefix', iconsDir)
     QApplication.instance().setStyleSheet(styleSheet)
     qss.close()
Пример #18
0
    def instanceSelected(self, index):
        index += 2 * self.schemaSelection.currentIndex()
        instanceFile = QFile(':/instance_%d.xml' % index)
        instanceFile.open(QFile.ReadOnly)
        instanceData = instanceFile.readAll()
        self.instanceEdit.setPlainText(encode_utf8(instanceData))

        self.validate()
Пример #19
0
    def readXmlDocument(self):
        root = QFileInfo(__file__).absolutePath()
        xml_file = QFile(root + '/examples.xml')
        xml_file.open(QFile.ReadOnly | QFile.Text)
        contents = xml_file.readAll().data()
        xml_file.close()

        self.contentsDoc = parseString(contents)
Пример #20
0
def write_pdf(fd, document):
    converter = document.pdfConverter()
    converter.setPDFOptions(converter.pdfOptions() | Poppler.PDFConverter.WithChanges)
    qfile = QFile()
    qfile.open(fd, QIODevice.WriteOnly)
    converter.setOutputDevice(qfile)
    if not converter.convert():
        raise IOError(converter.lastError())
Пример #21
0
 def test_write_error_real(self):
     """Test a real write error with /dev/full on supported systems."""
     qf = QFile('/dev/full')
     qf.open(QIODevice.WriteOnly | QIODevice.Unbuffered)
     dev = qtutils.PyQIODevice(qf)
     with pytest.raises(OSError, match='No space left on device'):
         dev.write(b'foo')
     qf.close()
Пример #22
0
    def __init__(self, parent):
        super(QKOSAbout, self).__init__(parent)
        gridlayout = QGridLayout(self)
        titlefont = QFont()
        titlefont.setPointSize(24)
        policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        label = QLabel("About QKeysOnScreen", self)
        label.setFont(titlefont)
        label.setSizePolicy(policy)
        gridlayout.addWidget(label, 0, 0)
        labelcopyright = QLabel("\u00a9 2015 Fredrick Brennan <*****@*****.**>")
        labelcopyright.setSizePolicy(policy)
        gridlayout.addWidget(labelcopyright, 1, 0)
        labeldesc = (
            "<p>QKeysOnScreen is a simple application intended for "
            + "presentations, video tutorials, and any other case where"
            + " you'd want to display the current state of the keyboard"
            + ' on the screen. For more information see our <a href="'
            + 'https://github.com/ctrlcctrlv/QKeysOnScreen">Github</a>'
            + " project."
        )
        qlabeldesc = QLabel(labeldesc)
        qlabeldesc.setWordWrap(True)
        gridlayout.addWidget(qlabeldesc, 2, 0)

        from PyQt5.QtCore import QT_VERSION_STR
        from PyQt5.Qt import PYQT_VERSION_STR
        import platform

        pyversion = ".".join([str(o) for o in sys.version_info])
        uname_result = platform.uname()
        uname = "{} {}".format(uname_result.system, uname_result.release)
        labelversions = (
            "<strong>Versions:</strong><br>Qt: {0}<br>PyQt: {1}" + "<br>Python: {2}<br>OS: {3}<br>QKeysOnScreen: 0.0.1"
        ).format(QT_VERSION_STR, PYQT_VERSION_STR, platform.python_version(), uname, platform.machine())
        qlabelversions = QLabel(labelversions)
        qlabelversions.setStyleSheet("border: 1px solid green")
        gridlayout.addWidget(qlabelversions, 0, 1)

        self.kb = get_keyboard_path()
        self.mouse = get_mouse_path()
        self.infoqlabel = QLabel(
            "<strong>Devices:</strong><br>" + "Our mouse is {0}<br/>Our keyboard is {1}".format(self.mouse, self.kb),
            self,
        )
        self.infoqlabel.setStyleSheet("border: 1px solid green")
        gridlayout.addWidget(self.infoqlabel, 2, 1)

        qte = QTextEdit(self)
        qte.setReadOnly(True)
        qfile = QFile(":/LICENSE")
        qfile.open(QIODevice.ReadOnly)
        qte.setPlainText(bytes(qfile.readAll()).decode("utf-8"))
        qfile.close()

        gridlayout.addWidget(qte, 3, 0, 1, 2)

        self.setLayout(gridlayout)
Пример #23
0
def setStyle(widget, aliasPath, objName=None):
    file_qss = QFile(aliasPath)
    file_qss.open(QFile.ReadOnly)
    ba = file_qss.readAll()
    s = bytes(ba.data()).decode()
    if objName:
        widget.setObjectName(objName)
    widget.setStyleSheet(s)
    file_qss.close()
Пример #24
0
def loadStyle(stylesheet):

    if stylesheet not in StyleSheets.keys():
        raise RuntimeError('Invalid stylesheet (%s)' %stylesheet)

    f = QFile(StyleSheets[stylesheet])
    f.open(QFile.ReadOnly | QFile.Text)
    ts = QTextStream(f)
    return  ts.readAll()
Пример #25
0
 def test_write_error_real(self):
     """Test a real write error with /dev/full on supported systems."""
     qf = QFile("/dev/full")
     qf.open(QIODevice.WriteOnly | QIODevice.Unbuffered)
     dev = qtutils.PyQIODevice(qf)
     with pytest.raises(OSError) as excinfo:
         dev.write(b"foo")
     qf.close()
     assert str(excinfo.value) == "No space left on device"
Пример #26
0
 def clickAction_styleLoad(self):
     fname, filter = QFileDialog.getOpenFileName(self, "QT스타일시트파일 불러오기", '.', "Qt-StyleSheet(*.qss)")
     if fname:
         file = QFile(fname)
         file.open(QFile.ReadOnly)
         styleSheet = file.readAll()
         styleSheet = str(styleSheet, encoding='utf8') # Python v3.
         self.setStyleSheet(styleSheet)
         print ("test")
Пример #27
0
def ReadTextFile(filePath):

    file = QFile(filePath)
    file.open(QFile.ReadOnly | QFile.Text)
    textStream = QTextStream(file)
    data = textStream.readAll()
    file.close()

    return data
Пример #28
0
 def readFile(self, path, coding = "UTF-8"):
     """读取文件"""
     file = QFile(path)
     file.open(QIODevice.ReadOnly | QIODevice.Text)
     fin = QTextStream(file)
     fin.setCodec(coding)
     data = fin.readAll()
     file.close()
     return data
Пример #29
0
 def __createSpeedDialPage(self):
     """
     Private method to create the Speeddial page.
     
     @return prepared speeddial page (QByteArray)
     """
     if self._speedDialPage is None:
         htmlFile = QFile(":/html/speeddialPage.html")
         htmlFile.open(QFile.ReadOnly)
         html = bytes(htmlFile.readAll()).decode()
         
         html = (
             html.replace("@FAVICON@", "qrc:icons/ericWeb16.png")
             .replace("@IMG_PLUS@", "qrc:icons/plus.png")
             .replace("@IMG_CLOSE@", "qrc:icons/close.png")
             .replace("@IMG_EDIT@", "qrc:icons/edit.png")
             .replace("@IMG_RELOAD@", "qrc:icons/reload.png")
             .replace("@IMG_SETTINGS@", "qrc:icons/setting.png")
             .replace("@LOADING-IMG@", "qrc:icons/loading.gif")
             .replace("@BOX-BORDER@", "qrc:icons/box-border-small.png")
             
             .replace("@JQUERY@", "qrc:javascript/jquery.js")
             .replace("@JQUERY-UI@", "qrc:javascript/jquery-ui.js")
             
             .replace("@SITE-TITLE@", self.tr("Speed Dial"))
             .replace("@URL@", self.tr("URL"))
             .replace("@TITLE@", self.tr("Title"))
             .replace("@APPLY@", self.tr("Apply"))
             .replace("@CLOSE@", self.tr("Close"))
             .replace("@NEW-PAGE@", self.tr("New Page"))
             .replace("@TITLE-EDIT@", self.tr("Edit"))
             .replace("@TITLE-REMOVE@", self.tr("Remove"))
             .replace("@TITLE-RELOAD@", self.tr("Reload"))
             .replace("@TITLE-WARN@",
                      self.tr("Are you sure to remove this speed dial?"))
             .replace("@TITLE-FETCHTITLE@",
                      self.tr("Load title from page"))
             .replace("@SETTINGS-TITLE@",
                      self.tr("Speed Dial Settings"))
             .replace("@ADD-TITLE@", self.tr("Add New Page"))
             .replace("@TXT_NRROWS@",
                      self.tr("Maximum pages in a row:"))
             .replace("@TXT_SDSIZE@", self.tr("Change size of pages:"))
         )
         
         self._speedDialPage = Utilities.html_uencode(html)
     
     import Helpviewer.HelpWindow
     html = QByteArray(self._speedDialPage.encode("utf-8"))
     dial = Helpviewer.HelpWindow.HelpWindow.speedDial()
     
     html.replace("@INITIAL-SCRIPT@", dial.initialScript().encode("utf-8"))
     html.replace("@ROW-PAGES@", str(dial.pagesInRow()).encode("utf-8"))
     html.replace("@SD-SIZE@", str(dial.sdSize()).encode("utf-8"))
     
     return html
Пример #30
0
def ReadResourceTextFile(resFile):

    res = QResource(resFile)
    file = QFile(res.absoluteFilePath())
    file.open(QFile.ReadOnly | QFile.Text)
    textStream = QTextStream(file)
    data = textStream.readAll()
    file.close()

    return data
Пример #31
0
    def save(self):
        fileName, _ = QFileDialog.getSaveFileName(self)
        if fileName:
            outFile = QFile(fileName)
            if not outFile.open(QFile.WriteOnly | QFile.Text):
                QMessageBox.warning(
                    self,
                    "Codecs",
                    "Cannot write file %s:\n%s" %
                    (fileName, outFile.errorString()),
                )
                return

            action = self.sender()
            codecName = action.data()

            out = QTextStream(outFile)
            out.setCodec(codecName)
            out << self.textEdit.toPlainText()
Пример #32
0
    def load(self, f):
        if not QFile.exists(f):
            return False

        fh = QFile(f)
        if not fh.open(QFile.ReadOnly):
            return False

        data = fh.readAll()
        codec = QTextCodec.codecForHtml(data)
        unistr = codec.toUnicode(data)

        if Qt.mightBeRichText(unistr):
            self.textEdit.setHtml(unistr)
        else:
            self.textEdit.setPlainText(unistr)

        self.setCurrentFileName(f)
        return True
Пример #33
0
 def load_file(self, filename=''):
     # 加载文件
     if filename:
         try:
             # 打开文件读取内容写到当前页面
             inFile = QFile(filename)
             if inFile.open(QFile.ReadOnly | QFile.Text):
                 text = inFile.readAll()
                 text = str(text, encoding='utf-8')
                 self.tab.currentWidget().e_edit.setPlainText(text)
                 inFile.close()
                 return True
         except Exception as e:
             # 当打开错误时给予错误提示
             QMessageBox.warning(
                 self, "Load Error !",
                 "Failed to load {0}: {1}".format(filename, e))
             return False
     return False
Пример #34
0
    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
Пример #35
0
	def saveHtml(self, fileName):
		if not QFileInfo(fileName).suffix():
			fileName += ".html"
		try:
			_, htmltext, _ = self.currentTab.getDocumentForExport(includeStyleSheet=False,
			                                                      webenv=True)
		except Exception:
			return self.printError()
		htmlFile = QFile(fileName)
		result = htmlFile.open(QIODevice.WriteOnly)
		if not result:
			QMessageBox.warning(self, '',
				self.tr("Cannot save to file because it is read-only!"))
			return
		html = QTextStream(htmlFile)
		if globalSettings.defaultCodec:
			html.setCodec(globalSettings.defaultCodec)
		html << htmltext
		htmlFile.close()
Пример #36
0
    def openFileOnStart(self, path=None):
        if path:
            inFile = QFile(path)
            if inFile.open(QFile.ReadWrite | QFile.Text):
                text = inFile.readAll()

                try:
                    # Python v3.
                    text = str(text, encoding='utf8')
                except TypeError:
                    # Python v2.
                    text = str(text)
                self.editor.setPlainText(text)
                self.filename = path
                self.setModified(False)
                self.fname = QFileInfo(path).fileName()
                self.setWindowTitle(self.fname + "[*]")
                self.document = self.editor.document()
                self.setCurrentFile(self.filename)
Пример #37
0
    def setSampleText(self, index):
        if index == 0:
            self.setCustomSampleText()
            return True
        try:
            sample_name = self.ui.cmbTextSamples.itemText(index)
            stream = QFile(":/samples/" + sample_name + ".txt")
            if stream.open(QFile.ReadOnly):
                sample_text = str(stream.readAll(), 'utf-8')
                stream.close()
            else:
                print(stream.errorString())

            self.ui.textEdit.setText(sample_text)
        except:
            print("error on opining sample text resource file")

        self.refreshTextStyle()
        """
Пример #38
0
    def save(self):
        filename, _ = QFileDialog.getSaveFileName(self, "Choose a file name",
                                                  '.', "HTML (*.html *.htm)")
        if not filename:
            return

        file = QFile(filename)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, "Dock Widgets",
                "Cannot write file %s:\n%s." % (filename, file.errorString()))
            return

        out = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        out << self.textEdit.toHtml()
        QApplication.restoreOverrideCursor()

        self.statusBar().showMessage("Saved '%s'" % filename, 2000)
Пример #39
0
 def saveTempRS232File(self):
     self.tempRS232Filename = 'tempFile.rs232'
     exception = None
     fh = None
     try:
         fh = QFile(self.tempRS232Filename)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         stream << self.outputText.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
Пример #40
0
 def tofile(self, path):
     """Write the bloom filter to file object `f'. Underlying bits
     are written as machine values. This is much more space
     efficient than pickling the object."""
     # f.write(pack(self.FILE_FMT, self.error_rate, self.num_slices,
     #              self.bits_per_slice, self.capacity, self.count))
     # f.write(self.bitarray.bits)
     f = QFile(path)
     if f.open(QIODevice.WriteOnly):
         out = QDataStream(f)
         out.writeBytes(self.FILE_FMT)
         out.writeFloat(self.error_rate)
         out.writeInt(self.num_slices)
         out.writeInt(self.bits_per_slice)
         out.writeInt(self.capacity)
         out.writeInt(self.count)
         out << self.bitarray
         f.flush()
         f.close()
Пример #41
0
 def loadFile(self):
     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.editor.setPlainText(stream.readAll())
         self.editor.document().setModified(False)
     except EnvironmentError as e:
         QMessageBox.warning(
             self, "Python Editor -- Load Error",
             "Failed to load {0}: {1}".format(self.filename, e))
     finally:
         if fh is not None:
             fh.close()
     self.setWindowTitle("Python Editor - {0}".format(
         QFileInfo(self.filename).fileName()))
Пример #42
0
    def openBook(self):
        filename, _ = QFileDialog.getOpenFileName(self, "Choose a filename",
                                                  ".", "CTG (*.ctg *.PGN)")
        if not filename:
            return

        file = QFile(filename)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(
                self, "Chess Fighter Error",
                "Can't open the file {}:\n{}.".format(filename,
                                                      file.errorString()))
            return

        self.statusBar().showMessage("Opened Book: {}".format(filename), 2000)
        for l in self.bidirectionalListeners:
            event = {"Book_File": filename, "Origin": self.__class__}
            # self.parent(event)
            l()(event)
Пример #43
0
    def __savePageScreen(self):
        """
        Private slot to save the page screen.
        
        @return flag indicating success (boolean)
        """
        fileName = E5FileDialog.getSaveFileName(
            self, self.tr("Save Page Screen"), self.tr("screen.png"),
            self.tr("Portable Network Graphics File (*.png)"),
            E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
        if not fileName:
            return False

        if QFileInfo(fileName).exists():
            res = E5MessageBox.yesNo(
                self,
                self.tr("Save Page Screen"),
                self.tr("<p>The file <b>{0}</b> already exists."
                        " Overwrite it?</p>").format(fileName),
                icon=E5MessageBox.Warning)
            if not res:
                return False

        file = QFile(fileName)
        if not file.open(QFile.WriteOnly):
            E5MessageBox.warning(
                self, self.tr("Save Page Screen"),
                self.tr("Cannot write file '{0}:\n{1}.").format(
                    fileName, file.errorString()))
            return False

        res = self.__pagePixmap.save(file)
        file.close()

        if not res:
            E5MessageBox.warning(
                self, self.tr("Save Page Screen"),
                self.tr("Cannot write file '{0}:\n{1}.").format(
                    fileName, file.errorString()))
            return False

        return True
Пример #44
0
    def exportAsVCard(self):
        name = str(self.nameLine.text())
        address = self.addressText.toPlainText()

        nameList = name.split()

        if len(nameList) > 1:
            firstName = nameList[0]
            lastName = nameList[-1]
        else:
            firstName = name
            lastName = ""

        fileName, _ = QFileDialog.getSaveFileName(
            self, "Export Contact", "", "vCard Files (*.vcf);;All Files (*)")

        if not fileName:
            return

        out_file = QFile(fileName)

        if not out_file.open(QIODevice.WriteOnly):
            QMessageBox.information(self, "Unable to open file",
                                    out_file.errorString())
            return

        out_s = QTextStream(out_file)

        out_s << "BEGIN:VCARD" << "\n"
        out_s << "VERSION:2.1" << "\n"
        out_s << "N:" << lastName << ";" << firstName << "\n"
        out_s << "FN:" << " ".join(nameList) << "\n"

        address.replace(";", "\\;")
        address.replace("\n", ";")
        address.replace(",", " ")

        out_s << "ADR;HOME:;" << address << "\n"
        out_s << "END:VCARD" << "\n"

        QMessageBox.information(self, "Export Successful",
                                '"%s" has been exported as a vCard.' % name)
Пример #45
0
    def exportAsVCard(self):
        title = str(self.titleLine.text())
        memo = self.memoText.toPlainText()

        titleList = title.split()

        if len(titleList) > 1:
            firstName = nameList[0]
            lastName = nameList[-1]
        else:
            firstName = name
            lastName = ''

        fileName, _ = QFileDialog.getSaveFileName(
            self, "Export Contact", '', "vCard Files (*.vcf);;All Files (*)")

        if not fileName:
            return

        out_file = QFile(fileName)

        if not out_file.open(QIODevice.WriteOnly):
            QMessageBox.information(self, "Unable to open file",
                                    out_file.errorString())
            return

        out_s = QTextStream(out_file)

        out_s << 'BEGIN:VCARD' << '\n'
        out_s << 'VERSION:2.1' << '\n'
        out_s << 'N:' << lastName << ';' << firstName << '\n'
        out_s << 'FN:' << ' '.join(nameList) << '\n'

        address.replace(';', '\\;')
        address.replace('\n', ';')
        address.replace(',', ' ')

        out_s << 'ADR;HOME:;' << address << '\n'
        out_s << 'END:VCARD' << '\n'

        QMessageBox.information(self, "Export Successful",
                                "\"%s\" has been exported as a vCard." % name)
Пример #46
0
    def write(self, fileNameOrDevice, pages, pagesPerRow, speedDialSize):
        """
        Public method to write a speed dial data file.
        
        @param fileNameOrDevice name of the file to write (string)
            or device to write to (QIODevice)
        @param pages list of speed dial pages (list of Page)
        @param pagesPerRow number of pages per row (integer)
        @param speedDialSize size of the speed dial pages (integer)
        @return flag indicating success (boolean)
        """
        if isinstance(fileNameOrDevice, QIODevice):
            f = fileNameOrDevice
        else:
            f = QFile(fileNameOrDevice)
            if not f.open(QFile.WriteOnly):
                return False

        self.setDevice(f)
        return self.__write(pages, pagesPerRow, speedDialSize)
Пример #47
0
 def fileSave(self):
     if self.filename is None:
         return self.fileSaveAs()
     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.editor.toPlainText()
         self.editor.document().setModified(False)
     except EnvironmentError as e:
         QMessageBox.warning(self, "Python 编辑器 -- 保存失败",
                 "保存 {0} 失败,错误: {1}".format(self.filename, e))
         return False
     finally:
         if fh is not None:
             fh.close()
     return True
Пример #48
0
    async def onQrImageEncoded(self, ipfsop,
                               encrypt: bool,
                               imgPath: str):
        basename = os.path.basename(imgPath)
        file = QFile(imgPath)

        if encrypt:
            if not file.open(QIODevice.ReadOnly):
                return
            data = file.readAll().data()
            entry = await self.rsaEncryptSelf(data)
        else:
            entry = await ipfsop.addPath(imgPath, offline=True)

        if entry:
            # Link it, open it
            dst = self.pathQrCodesEncrypted if encrypt is True else \
                self.pathQrCodes
            await ipfsop.filesLink(entry, dst, name=basename)
            await self.ctx.app.resourceOpener.open(entry['Hash'])
Пример #49
0
    def onFileSave(self):
        if not self.m_filePath:
            self.onFileSaveAs()
            return

        f = QFile(self.m_filePath)
        if not f.open(QIODevice.WriteOnly | QIODevice.Text):
            QMessageBox.warning(
                self,
                self.windowTitle(),
                self.tr("Could not write to file %s: %s" %
                        (QDir.toNativeSeparators(
                            self.m_filePath), f.errorString())),
            )
            return

        text = QTextStream(f)
        text << self.editor.toPlainText()

        self.editor.document().setModified(False)
Пример #50
0
def orbitScripts(connParams):
    scripts = []
    jsFile = QFile(':/share/js/orbit-db/orbitdb.js')
    if not jsFile.open(QFile.ReadOnly):
        return
    scriptJsIpfs = QWebEngineScript()
    scriptJsIpfs.setName('orbit-db')
    scriptJsIpfs.setSourceCode(jsFile.readAll().data().decode('utf-8'))
    scriptJsIpfs.setWorldId(QWebEngineScript.MainWorld)
    scriptJsIpfs.setInjectionPoint(QWebEngineScript.DocumentCreation)
    scriptJsIpfs.setRunsOnSubFrames(True)
    scripts.append(scriptJsIpfs)

    script = QWebEngineScript()
    script.setSourceCode('\n'.join([
        "document.addEventListener('DOMContentLoaded', function () {",
        "window.orbitdb = new OrbitDB(window.ipfs)", "})"
    ]))
    script.setWorldId(QWebEngineScript.MainWorld)
    return scripts
Пример #51
0
    def write(self, fileNameOrDevice, logins, forms, nevers):
        """
        Public method to write an login data file.
        
        @param fileNameOrDevice name of the file to write (string)
            or device to write to (QIODevice)
        @param logins dictionary with login data (user name, password)
        @param forms list of forms data (list of LoginForm)
        @param nevers list of URLs to never store data for (list of strings)
        @return flag indicating success (boolean)
        """
        if isinstance(fileNameOrDevice, QIODevice):
            f = fileNameOrDevice
        else:
            f = QFile(fileNameOrDevice)
            if not f.open(QFile.WriteOnly):
                return False

        self.setDevice(f)
        return self.__write(logins, forms, nevers)
Пример #52
0
    def _grep_file(self, file_path, file_name):
        """Search for each line inside the file"""
        file_obj = QFile(file_path)
        if not file_obj.open(QFile.ReadOnly):
            return
        stream = QTextStream(file_obj)
        lines = []
        append = lines.append
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not stream.atEnd():
            column = self.search_pattern.indexIn(line)
            if column != -1:
                append((line_index, line))
            # Take the next line
            line = stream.readLine()
            line_index += 1

        p = os.path.join(self.root_dir, file_path)
        self.resultAvailable.emit((p, lines))
Пример #53
0
def ipfsClientScripts(connParams):
    scripts = []
    jsFile = QFile(':/share/js/ipfs-http-client/index.min.js')
    if not jsFile.open(QFile.ReadOnly):
        return

    scriptJsIpfs = QWebEngineScript()
    scriptJsIpfs.setName('ipfs-http-client')

    libCode = jsFile.readAll().data().decode('utf-8')
    libCode += "\n"
    libCode += ipfsInjScript.format(host=connParams.host,
                                    port=connParams.apiPort)

    scriptJsIpfs.setSourceCode(libCode)
    scriptJsIpfs.setWorldId(QWebEngineScript.MainWorld)
    scriptJsIpfs.setInjectionPoint(QWebEngineScript.DocumentCreation)
    scriptJsIpfs.setRunsOnSubFrames(True)
    scripts.append(scriptJsIpfs)
    return scripts
Пример #54
0
 def runFile(self):
     myCmd0= 'python /Users/tania/Desktop/Desktop/ORIGINAL/Code/Tugas_Akhir/AksaraBatak/Translator/converter.py'
     myCmd = 'python test_model.py ./models/CNN.pth ./models/voc-model-labels.txt ./outs/ImageSets/test.txt'
     myCmd2 = 'python /Users/tania/Desktop/Desktop/ORIGINAL/Code/Tugas_Akhir/AksaraBatak/BFS/bfs.py'
     os.system(myCmd0)
     os.system(myCmd)
     os.system(myCmd2)     
     
     file = QFile("/Users/tania/Desktop/Desktop/ORIGINAL/Code/Tugas_Akhir/AksaraBatak/BFS/outputBFS.txt")
     
     if file.open(QIODevice.ReadOnly | QIODevice.Text):
         stream = QTextStream(file)
         while not stream.atEnd():   
             line = file.readLine()
             line.append(stream.readLine()+"\n")
             encodedString = line.append(stream.readLine()+"\n")
             codec = QTextCodec.codecForName("KOI8-R")
             string = codec.toUnicode(encodedString)
             self.results.setText(string)
     file.close();
Пример #55
0
 def daily_source_file_reply(self):
     """ 获取日交易源数据返回 """
     reply = self.sender()
     if reply.error():
         reply.deleteLater()
         self.spider_finished.emit("失败:" + str(reply.error()), True)
         return
     save_path = os.path.join(
         LOCAL_SPIDER_SRC,
         'dce/daily/{}.xls'.format(self.date.strftime("%Y-%m-%d")))
     file_data = reply.readAll()
     file_obj = QFile(save_path)
     is_open = file_obj.open(QFile.WriteOnly)
     if is_open:
         file_obj.write(file_data)
         file_obj.close()
     reply.deleteLater()
     self.spider_finished.emit(
         "获取大商所{}日交易数据保存到文件成功!".format(self.date.strftime("%Y-%m-%d")),
         True)
Пример #56
0
def initDosenPage(window, auth):
    global _navbar_D_1, _content_D_1, _mainVLayout_D_1, _auth
    # Save authentication profile
    _auth = auth
    # Load layout ui
    uifile = QFile(":ui/ui/dosen_layout.ui")
    uifile.open(QFile.ReadOnly)
    uic.loadUi(uifile, window)
    uifile.close()
    # Get object from layout ui
    _mainVLayout_D_1 = window.findChild(QVBoxLayout, "mainVLayout_D_1")

    # Create and load navbar widget
    _navbar_D_1 = QWidget()
    uifile = QFile(":ui/ui/dosen_navbar.ui")
    uifile.open(QFile.ReadOnly)
    uic.loadUi(uifile, _navbar_D_1)
    uifile.close()
    # Get object from navbar ui
    _logoSiak_D_2 = _navbar_D_1.findChild(QLabel, "logoSiak_D_2")
    _berandaButton_D_2 = _navbar_D_1.findChild(QPushButton, "berandaButton_D_2")
    _pengaturanButton_D_2 = _navbar_D_1.findChild(QPushButton, "pengaturanButton_D_2")
    _buatAkunMhsButton_D_2 = _navbar_D_1.findChild(QPushButton, "buatAkunMhsButton_D_2")
    # Asserting object findChild successful
    assert _berandaButton_D_2 is not None
    assert _pengaturanButton_D_2 is not None
    assert _buatAkunMhsButton_D_2 is not None
    # Set logo
    _logoSiak_D_2.setPixmap(QPixmap(":img/img/logo_siak_full.png"))

    # Create and load content dashboard widget
    _content_D_1 = QWidget()
    uifile = QFile(":ui/ui/dosen_content_dashboard.ui")
    uifile.open(QFile.ReadOnly)
    uic.loadUi(uifile, _content_D_1)
    uifile.close()
    # Simulate berandaButtonClicked
    berandaButtonClicked()

    # Set widgets to layout
    _mainVLayout_D_1.addWidget(_navbar_D_1)
    _mainVLayout_D_1.addWidget(_content_D_1)
    _navbar_D_1.setFixedHeight(200)
    _content_D_1.setMinimumHeight(window.frameGeometry().height() - 200)

    # Set connection
    _berandaButton_D_2.clicked.connect(lambda: berandaButtonClicked())
    _pengaturanButton_D_2.clicked.connect(lambda: pengaturanButtonClicked())
    _buatAkunMhsButton_D_2.clicked.connect(lambda: buatAkunMhsButtonClicked())
Пример #57
0
 def __readTxt(self, file_name: str) -> bool:
     """
     :param file_name: str,txt文件名
     :return: bool,是否成功
     """
     file_device = QFile(file_name)
     if not file_device.exists():
         return False
     if not file_device.open(QIODevice.ReadOnly | QIODevice.Text):
         return False
     try:
         file_stream = QTextStream(file_device)
         file_stream.setAutoDetectUnicode(True)  # 自动检测unicode
         file_stream.setCodec('utf-8')  # 不然不能读取汉字
         while not file_stream.atEnd():
             line_str = file_stream.readLine()  # 一行行读,读出来就是str
             self.__import2Table(line_str)
     finally:
         file_device.close()
     return True
Пример #58
0
 def loadFromFile(self, filename):  # 打开文件
     self.currentFilePath = filename
     self.setWindowTitle(filename)
     self.__fileOpened = True
     baseFilename = os.path.basename(filename)  # 去掉目录后的文件名
     self.setWindowTitle(baseFilename)
     fileDevice = QFile(filename)
     if not fileDevice.exists():
         return False
     if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
         return False
     try:
         self.tE.clear()
         qtBytes = fileDevice.readAll()  # 返回QByteArray类型
         pyBytes = bytes(qtBytes.data())  # 将QByteArray转换为bytes类型
         text = pyBytes.decode("utf-8")  # 用utf-8编码为字符串
         self.tE.setText(text)
     finally:
         fileDevice.close()
     return True
Пример #59
0
    def loadFile(self, fileName):

        file = QFile(fileName)

        #rfile=file.open(QFile.ReadOnly | QFile.Text)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(
                self, "Application",
                "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return

        #

        inf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.textEdit.setPlainText(inf.readAll())
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        self.statusBar().showMessage("File loaded", 2000)
Пример #60
0
    def __addEngineByFile(self, filename):
        """
        Private method to add a new search engine given a filename.
        
        @param filename name of a file containing the engine definition
            (string)
        @return flag indicating success (boolean)
        """
        file_ = QFile(filename)
        if not file_.open(QIODevice.ReadOnly):
            return False

        from .OpenSearchReader import OpenSearchReader
        reader = OpenSearchReader()
        engine = reader.read(file_)

        if not self.__addEngineByEngine(engine):
            return False

        return True