コード例 #1
0
 def load_ui(self):
     loader = QUiLoader()
     path = os.fspath(Path(__file__).resolve().parent / "form.ui")
     ui_file = QFile(path)
     ui_file.open(QFile.ReadOnly)
     loader.load(ui_file, self)
     ui_file.close()
コード例 #2
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")
コード例 #3
0
def load_ui(ui_file, parent=None):
    loader = QUiLoader()
    file = QFile(ui_file)
    file.open(QFile.ReadOnly)
    myWidget = loader.load(file, None)
    myWidget.show()
    file.close()
    myWidget.show()
    return myWidget
コード例 #4
0
ファイル: main.py プロジェクト: ChaunceyXu/Bulls-and-Cows
    def __init__(self, parent=None):
        #load ui
        ui_file = QFile("mainwindow.ui")
        ui_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        self.window = loader.load(ui_file)

        #init game
        self.gameInit()
        self.window.actionrule.triggered.connect(self.helpText)
        self.window.btnCheck.clicked.connect(self.CheckNum)
        self.window.btnRetry.clicked.connect(self.gameInit)
        self.window.show()
コード例 #5
0
ファイル: IOXML.py プロジェクト: nus-ncl/Client
def importXmlDOM(filename):
    '''
	The QDomDocument class represents the entire XML document
	The DOM classes that will be used most often are QDomNode , QDomDocument , QDomElement and QDomText
	The DOM tree might end up reserving a lot of memory if the XML document is big. For such documents,
	the QXmlStreamReaderor the QXmlQuery classes might be better solutions.
	:param filename: filename_path
	:return: document
	'''

    document = QDomDocument()
    error = None
    file = None
    try:
        # instantiate a device(QFile) specified by filename
        file = QFile(filename)
        if not file.open(QIODevice.ReadOnly):
            raise IOError(str(file.errorString()))
        # setContent parses an XML file and creates the DOM tree that represents the document
        if not document.setContent(file):
            raise ValueError("could not parse XML")
    except (IOError, OSError, ValueError) as e:
        error = "Failed to import: {0}".format(e)
    finally:
        if file is not None:
            file.close()
        if error is not None:
            print(error)
        return document
コード例 #6
0
    def __init__(self):

        ui_file_name = "record_frame.ui"
        ui_file = QFile(ui_file_name)
        if not ui_file.open(QIODevice.ReadOnly):
            print("can not open file " + ui_file_name)
            sys.exit(-1)
        self.window = QUiLoader().load(ui_file)
        ui_file.close()
        self._component_bind()
        self.window.show()
        self.status = "Ready"
        self.record = []
        self.current_mill_time = current_time()
        self.delay = int(self.window.record_time_stepper.value())
        self.run_times = int(self.window.run_time_stepper.value())
        self.start_hot_key = self.window.run_hot_key.currentText()
        self.stop_hot_key = self.window.stop_hot_key.currentText()
        # self.window.record_script
        self.window.run_hot_key.addItems(self.HOT_KEYS)
        self.window.run_hot_key.setCurrentIndex(8)
        self.window.stop_hot_key.addItems(self.HOT_KEYS)
        self.window.stop_hot_key.setCurrentIndex(9)
        self._refresh_scripts()
        self.window.status.setText(self.status)

        self.hookManager = pyWinhook.HookManager()
        self.hookManager.MouseAll = self._mouse_move_handler
        self.hookManager.KeyAll = self._keyboard_click_handler
        self.hookManager.HookKeyboard()
        self.hookManager.HookMouse()
コード例 #7
0
ファイル: persepolis.py プロジェクト: sunshinenny/persepolis
    def setPersepolisColorScheme(self, color_scheme):
        self.persepolis_color_scheme = color_scheme
        if color_scheme == 'Dark Fusion':
            dark_fusion = DarkFusionPalette()
            self.setPalette(dark_fusion)
            file = QFile(":/dark_style.qss")
            file.open(QFile.ReadOnly | QFile.Text)
            stream = QTextStream(file)
            self.setStyleSheet(stream.readAll())

        elif color_scheme == 'Light Fusion':
            light_fusion = LightFusionPalette()
            self.setPalette(light_fusion)
            file = QFile(":/light_style.qss")
            file.open(QFile.ReadOnly | QFile.Text)
            stream = QTextStream(file)
            self.setStyleSheet(stream.readAll())
コード例 #8
0
    def __init__(self):
        super().__init__()

        self.setGeometry(50, 50, 200, 200)
        self.setWindowTitle('Awesome File Manager')

        ui_file = QFile("mainwindow.ui")
        ui_file.open(QFile.ReadOnly)

        loader = QUiLoader()
        self.window = loader.load(ui_file)

        self.window.comboBox.setItemText(0, 'first filter')

        files = QFileDialog.getOpenFileNames(self)
        btn_file = QPushButton('Open', self)
        for file in files[0]:
            btn_file.clicked.connect(main(file))
コード例 #9
0
def load_ui(name, custom_widgets=[], parent=None):
    loader = QUiLoader()
    for cw in custom_widgets:
        loader.registerCustomWidget(cw)
    path = os.path.join(os.path.dirname(__file__), "ui", name)
    ui_file = QFile(path)
    if not ui_file.open(QFile.ReadOnly):
        logging.critical("Cannot open {}: {}".format(path,
                                                     ui_file.errorString()))
        sys.exit(-1)
    ui = loader.load(ui_file, parent)
    ui_file.close()
    return ui
コード例 #10
0
    def open_file(self, path=""):
        file_name = path

        if not file_name:
            file_name, _ = QFileDialog.getOpenFileName(
                self, self.tr("Open File"), "",
                "qmake Files (*.pro *.prf *.pri)")

        if file_name:
            inFile = QFile(file_name)
            if inFile.open(QFile.ReadOnly | QFile.Text):
                stream = QTextStream(inFile)
                self._editor.setPlainText(stream.readAll())
コード例 #11
0
ファイル: about.py プロジェクト: sunshinenny/persepolis
    def __init__(self, persepolis_setting):
        super().__init__(persepolis_setting)

        self.persepolis_setting = persepolis_setting

        # setting window size and position
        size = self.persepolis_setting.value('AboutWindow/size',
                                             QSize(545, 375))
        position = self.persepolis_setting.value('AboutWindow/position',
                                                 QPoint(300, 300))

        # read translators.txt files.
        # this file contains all translators.
        f = QFile(':/translators.txt')

        f.open(QIODevice.ReadOnly | QFile.Text)
        f_text = QTextStream(f).readAll()
        f.close()

        self.translators_textEdit.insertPlainText(f_text)

        self.resize(size)
        self.move(position)
コード例 #12
0
    def loadFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(
                self, "MateWriter",
                "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)
コード例 #13
0
    def __init__(self):
        super(MainWindow, self).__init__()
        loader = QUiLoader()
        path = os.path.join(os.path.dirname(__file__), "main_window.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        self.window = loader.load(ui_file, self)
        ui_file.close()
        self.week = 1
        self.sel_block = (-1, -1)
        self.group = 'WCY18IJ5S1'
        self.blocks = list()
        self.loading_widget = None

        self.main_widget = self.window.findChild(QWidget, 'college_schedule')
        self.table_widget = self.window.findChild(QTableWidget, 'table_widget')
        self.next_week = self.window.findChild(QPushButton, 'next_week')
        self.previous_week = self.window.findChild(QPushButton, 'previous_week')
        self.save_note_button = self.window.findChild(QPushButton, 'save_note')
        self.group_box = self.window.findChild(QComboBox, 'group_box')
        self.download_button = self.window.findChild(QPushButton, 'download_data')
        self.note = self.window.findChild(QTextEdit, 'note')

        self.next_week.clicked.connect(lambda: self.get_week_click(self.week + 1))
        self.previous_week.clicked.connect(lambda: self.get_week_click(self.week - 1))
        self.save_note_button.clicked.connect(self.save_note_click)
        self.download_button.clicked.connect(lambda: self.load_data(True))
        self.table_widget.cellClicked.connect(self.block_click)
        self.table_widget.cellDoubleClicked.connect(self.block_double_click)
        self.group_box.currentTextChanged.connect(self.group_change)
        self.loading_signal.connect(self.loading_slot)
        self.set_blocks_signal.connect(self.set_blocks_slot)

        self.scraper = Scraper()
        t = threading.Thread(target=lambda: self.scraper.start(self, self.group))
        t.start()
コード例 #14
0
    def saveFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, "MateWriter",
                "Cannot write file %s:\n%s." % (fileName, file.errorString()))
            return False

        outf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outf << self.textEdit.toPlainText()
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        self.statusBar().showMessage("File saved", 2000)
        return True
コード例 #15
0
ファイル: test_parser.py プロジェクト: xmarduel/pycut
    def loadFile(self):
        file = QFile(self.filename)

        if not file.open(QIODevice.ReadOnly):
            print("Can't open file:\n" + self.filename)
            return

        # Prepare text stream
        textStream = QTextStream(file)

        # Read lines
        data = []
        while not textStream.atEnd():
            data.append(textStream.readLine())

        # Load lines
        self.loadData(data)
コード例 #16
0
    def loadFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(
                self, "MDI",
                "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return False

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

        self.setCurrentFile(fileName)

        self.document().contentsChanged.connect(self.documentWasModified)

        return True
コード例 #17
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)
コード例 #18
0
ファイル: uiControl.py プロジェクト: Roy-Kid/paperSpider
    def initUI(self, uiname, mode):
        # release mode
        # TODO: convert .ui to py code
        app = QApplication(sys.argv)

        # debug mode
        if mode == 'debug':
            ui_file_name = uiname
            ui_file = QFile(ui_file_name)
            if not ui_file.open(QIODevice.ReadOnly):
                print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
                sys.exit(-1)
            loader = QUiLoader()
            window = loader.load(ui_file)
            ui_file.close()
            if not window:
                print(loader.errorString())
                sys.exit(-1)
            window.show()

        return app, window
コード例 #19
0
ファイル: test_gcodeparser.py プロジェクト: xmarduel/pycut
    def loadFile(self, fileName):
        file = QFile(fileName)

        if not file.open(QIODevice.ReadOnly):
            QMessageBox.critical(self, self.windowTitle(),
                                 "Can't open file:\n" + fileName)
            return

        # Set filename
        self.m_programFileName = fileName

        # Prepare text stream
        textStream = QTextStream(file)

        # Read lines
        data = []
        while not textStream.atEnd():
            data.append(textStream.readLine())

        # Load lines
        self.loadData(data)
コード例 #20
0
 def load_items(self, file_name: str, gim):
     input_file = QFile(file_name)
     if input_file.open(QIODevice.ReadOnly):
         input_stream = QDataStream(input_file)
         while not input_stream.atEnd():
             item_type = input_stream.readInt8()
             item_name = input_stream.readString()
             if item_type == QGraphicsRectItem.type(QGraphicsRectItem()):
                 rect = QGraphicsRectItem()
                 self.input_to_rect_item(input_stream, rect)
                 self.scene.addItem(rect)
                 gim.append_shape(rect, rect.type(), rect.pen(),
                                  rect.brush())
                 print("Rectangle loaded")
             elif item_type == QGraphicsEllipseItem.type(
                     QGraphicsEllipseItem()):
                 ellipse = QGraphicsEllipseItem()
                 self.input_to_rect_item(input_stream, ellipse)
                 self.scene.addItem(ellipse)
                 gim.append_shape(ellipse, ellipse.type(), ellipse.pen(),
                                  ellipse.brush())
                 print("Ellipse loaded")
             elif item_type == QGraphicsPolygonItem.type(
                     QGraphicsPolygonItem()):
                 polygon = QGraphicsPolygonItem()
                 self.input_to_polygon_item(input_stream, polygon)
                 self.scene.addItem(polygon)
                 gim.append_shape(polygon, polygon.type(), polygon.pen(),
                                  polygon.brush())
                 print("l polygon")
             elif item_type == QGraphicsLineItem.type(QGraphicsLineItem()):
                 line = QGraphicsLineItem()
                 self.input_to_line_item(input_stream, line)
                 self.scene.addItem(line)
                 gim.append_shape(line, line.type(), line.pen(),
                                  QBrush(Qt.black))
                 print("Line loaded")
             gim.return_shapes()[-1].name = item_name
             ItemsInputOutput.set_item_flags(self.scene)
         input_file.close()
コード例 #21
0
 def save_items(self, file_name: str, gim):
     output_file = QFile(file_name)
     if output_file.open(QIODevice.WriteOnly):
         output_stream = QDataStream(output_file)
         scene_items_reverse = self.scene.items()
         scene_items_reverse.reverse()
         for item in scene_items_reverse:
             output_stream.writeInt8(item.type())
             output_stream.writeString(gim.get_name_from_reference(item))
             if type(item) == QGraphicsRectItem:
                 self.output_from_rect_item(output_stream, item)
                 print("rect saved!")
             elif type(item) == QGraphicsEllipseItem:
                 self.output_from_rect_item(output_stream, item)
                 print("ellipse saved!")
             elif type(item) == QGraphicsPolygonItem:
                 self.output_from_polygon_item(output_stream, item)
                 print("polygon saved!")
             elif type(item) == QGraphicsLineItem:
                 self.output_from_line_item(output_stream, item)
                 print("line saved!")
         output_file.close()
コード例 #22
0
    def __init__(self):
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
        app = QApplication(sys.argv)
        app.setStyle(QStyleFactory.create('Fusion'))

        ui_file_name = '%s.ui' % Path(__file__).stem
        ui_file = QFile(ui_file_name)
        if not ui_file.open(QIODevice.ReadOnly):
            print('Cannot open %s: %s' % (ui_file_name, ui_file.errorString()))
            sys.exit(-1)

        loader = QUiLoader()
        self.window = loader.load(ui_file)
        ui_file.close()
        if not self.window:
            print(loader.errorString())
            sys.exit(-1)

        self.connect()
        self.setting()

        self.window.show()

        sys.exit(app.exec())
コード例 #23
0
ファイル: Asn1scc.py プロジェクト: esa/opengeode
def parse_asn1(*files, **options):
    ''' Call the ASN.1 parser on a number of files, and return the module
        containing the AST
        This function uses QProcess to launch the ASN.1 compiler because
        the subprocess module from Python has issues on the Windows platform
    '''
    if '-g' in sys.argv:
        os.environ["PROJECT_CACHE"] = './debug'

    # use basic caching to avoid re-parsing when loading the model
    project_cache = os.getenv("PROJECT_CACHE")
    if project_cache is not None and not os.path.isdir(project_cache):
        try:
            print(f"[INFO] Creating cache folder {project_cache}")
            os.makedirs(project_cache)
        except OSError:
            raise TypeError(
                f'''The configured cache folder "{project_cache} " \
                is not there and could not be created\n''')
    # make sure the same files are not parsed more than once if not modified
    filehash = hashlib.md5()
    file_list = sorted(list(*files))
    try:
        for each in file_list:
            filehash.update(open(each).read().encode('utf-8'))
            # also hash the file path: it is used in the AST, so it is
            # not enough to hash the content of the ASN.1 files, as two sets
            # of input files may have the same hash
            filehash.update(each.encode('utf-8'))
    except IOError as err:
        raise TypeError(str(err))
    new_hash = filehash.hexdigest()

    # names of the files that will be generated by asn1scc and then parsed
    out_py_name = new_hash + ".py"
    out_html_name = new_hash + ".html"

    if new_hash in AST.keys():
        return AST[new_hash]
    elif project_cache is not None:
        outdir = project_cache
    elif project_cache is None:
        outdir = tempfile.mkdtemp()

    # to allow the import
    sys.path.append(outdir)

    ast_version = options.get('ast_version', ASN1.UniqueEnumeratedNames)
    rename_policy = options.get('rename_policy', ASN1.NoRename)
    flags = options.get('flags', [ASN1.AstOnly])
    pprint = options.get('pretty_print', False)
    extraflags = options.get('extraflags', [])
    assert isinstance(ast_version, ASN1)
    assert isinstance(rename_policy, ASN1)
    assert isinstance(flags, list)
    path_to_asn1scc = spawn.find_executable('asn1scc')

    if not path_to_asn1scc:
        raise TypeError('ASN.1 Compiler (asn1scc) not found in path')
    binary = path_to_asn1scc
    asn1scc_root = os.path.abspath(os.path.dirname(binary))

    if os.name == 'nt':
        # On windows, remove the drive letter, workaround to ASN1SCC bug
        outdir = outdir[2:]
        asn1scc_root = asn1scc_root[2:]

    # The two possible files that can be generated with complete path:
    py_filepath = outdir + os.sep + out_py_name
    html_filepath = outdir + os.sep + out_html_name

    # call the ASN.1 compiler only if there is no existing cached file
    if project_cache is None or not os.path.exists(py_filepath):
        stg = asn1scc_root + os.sep + 'python.stg'

        if pprint:
            # Generate an html file with pretty-printed ASN.1 types
            stg_qrc = QFile(':misc/pretty_print_asn1.stg')
            stg_qrc.open(QIODevice.ReadOnly)
            content = stg_qrc.readAll()
            stgfile = outdir + os.sep + 'pretty_print_asn1.stg'
            with open(stgfile, 'wb') as tmpfile:
                tmpfile.write(content.data())
            html = ['-customIcdUper', stgfile + '::' + html_filepath]
        else:
            html = []
        args = [
            '-customStgAstVersion',
            str(ast_version.value), '--field-prefix', 'AUTO', '-customStg',
            stg + '::' + py_filepath, '-renamePolicy',
            str(rename_policy.value)
        ] + html + extraflags + file_list
        asn1scc = QProcess()
        LOG.debug(os.getcwd())
        LOG.debug(args)
        LOG.debug(binary + ' ' + ' '.join(args))
        LOG.debug(f"Python AST: {py_filepath}")
        asn1scc.start(binary, args)

        _ = waitfor_qprocess(asn1scc, "ASN.1 Compiler")

    ast = importlib.import_module(new_hash)
    AST[new_hash] = ast
    if pprint:
        # add the path to the optionally-generated pretty-printed HTML file
        ast.html = html_filepath
    return ast
コード例 #24
0
            'ffmpeg', os.path.join(cwd, spectrogram_filename),
            os.path.join(cwd, master_filename), mp4_metadata,
            os.path.join(cwd, mp4_filename))
        mp4_command = mp4_command.replace('\\', '/')
        print('mp4_command:            ' + mp4_command)
        os.system(mp4_command)
        os.system('rm *wavuntagged.wav')
        os.system('{} {}'.format(soundfile_editor, master_filename))
        print("")
    except:
        traceback.print_exc()


application = QApplication(sys.argv)
ui_file = QFile(piece_ui_filepath)
if not ui_file.open(QIODevice.ReadOnly):
    print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
    sys.exit(-1)
ui_loader = QUiLoader()
main_window = ui_loader.load(ui_file)
print("main_window: {} {}".format(main_window, type(main_window)))
ui_file.close()
if not main_window:
    print(loader.errorString())
    sys.exit(-1)
'''
Each instance of this class encapsulates one Csound control channel along with  
the Qt Widget that manages it. The methods of this class should have cases for 
handling different types of Csound channels (strings or numbers), and 
different types of Qt Widgets.