コード例 #1
0
ファイル: DiffDialog.py プロジェクト: paulmadore/Eric-IDE
 def __generateContextDiff(self, a, b, fromfile, tofile,
                           fromfiledate, tofiledate):
     """
     Private slot to generate a context diff output.
     
     @param a first sequence of lines (list of strings)
     @param b second sequence of lines (list of strings)
     @param fromfile filename of the first file (string)
     @param tofile filename of the second file (string)
     @param fromfiledate modification time of the first file (string)
     @param tofiledate modification time of the second file (string)
     """
     paras = 0
     for line in context_diff(a, b, fromfile, tofile,
                              fromfiledate, tofiledate):
         if line.startswith('+ '):
             format = self.cAddedFormat
         elif line.startswith('- '):
             format = self.cRemovedFormat
         elif line.startswith('! '):
             format = self.cReplacedFormat
         elif (line.startswith('*** ') or line.startswith('--- ')) and \
                 paras > 1:
             format = self.cLineNoFormat
         else:
             format = self.cNormalFormat
         self.__appendText(line, format)
         paras += 1
         if not (paras % self.updateInterval):
             QApplication.processEvents()
         
     if paras == 0:
         self.__appendText(
             self.tr('There is no difference.'), self.cNormalFormat)
コード例 #2
0
ファイル: homepage.py プロジェクト: GuLinux/PySpectrum
 def download_catalogs(self):
     dialog = QDialog()
     dialog.setWindowTitle('Download Catalogs')
     dialog.setLayout(QVBoxLayout())
     dialog.layout().addWidget(QLabel('Select catalogues to be downloaded'))
     checkboxes = dict([(c, QCheckBox(c)) for c in self.reference_catalogues.catalogues])
     for name, checkbox in checkboxes.items():
         checkbox.setChecked(True)
         dialog.layout().addWidget(checkbox)
     buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
     buttonbox.accepted.connect(dialog.accept)
     buttonbox.rejected.connect(dialog.reject)
     dialog.layout().addWidget(buttonbox)
     if dialog.exec() == QDialog.Rejected:
         return
     for cat, checkbox in checkboxes.items():
         if not checkbox.isChecked():
             continue
         spectra = self.reference_catalogues.spectra(cat)
         progress = QProgressDialog('Downloading spectra from catalog {}'.format(cat), 'Cancel', 0, len(spectra))
         progress.setWindowTitle('Downloading catalogs')
         progress.setWindowModality(Qt.WindowModal)
         progress.show()
         for index, spectrum in enumerate(spectra):
             progress.setValue(index)
             if progress.wasCanceled():
                 return;
             QApplication.instance().processEvents()
             self.reference_catalogues.fits(spectrum)
コード例 #3
0
 def __compileAllResources(self):
     """
     Private method to compile all resources to source files.
     """
     if self.hooks["compileAllResources"] is not None:
         self.hooks["compileAllResources"](self.project.pdata["RESOURCES"])
     else:
         numResources = len(self.project.pdata["RESOURCES"])
         progress = E5ProgressDialog(
             self.tr("Compiling resources..."),
             self.tr("Abort"), 0, numResources,
             self.tr("%v/%m Resources"), self)
         progress.setModal(True)
         progress.setMinimumDuration(0)
         progress.setWindowTitle(self.tr("Resources"))
         i = 0
         
         for fn in self.project.pdata["RESOURCES"]:
             progress.setValue(i)
             if progress.wasCanceled():
                 break
             proc = self.__compileQRC(fn, True, progress)
             if proc is not None:
                 while proc.state() == QProcess.Running:
                     QApplication.processEvents()
                     QThread.msleep(300)
                     QApplication.processEvents()
             else:
                 break
             i += 1
             
         progress.setValue(numResources)
コード例 #4
0
 def start(self, path):
     """
     Public slot to start the tags command.
     
     @param path name of directory to list conflicts for (string)
     """
     self.errorGroup.hide()
     QApplication.processEvents()
         
     self.intercept = False
     dname, fname = self.vcs.splitPath(path)
     
     # find the root of the repo
     self.__repodir = dname
     while not os.path.isdir(
             os.path.join(self.__repodir, self.vcs.adminDir)):
         self.__repodir = os.path.dirname(self.__repodir)
         if os.path.splitdrive(self.__repodir)[1] == os.sep:
             return
     
     self.activateWindow()
     self.raise_()
     
     self.conflictsList.clear()
     self.__started = True
     self.__getEntries()
コード例 #5
0
ファイル: main.py プロジェクト: SukharevAndrey/GameOfLife
def main():
    app = QApplication(sys.argv)
    w = MainWidget()
    w.setWindowTitle("Игра \"Жизнь\"")
    w.setFixedSize(w.geometry().width(), w.geometry().height())
    w.show()
    return app.exec_()
コード例 #6
0
ファイル: SvnDialogMixin.py プロジェクト: pycom/EricShort
 def _clientLoginCallback(self, realm, username, may_save):
     """
     Protected method called by the client to get login information.
     
     @param realm name of the realm of the requested credentials (string)
     @param username username as supplied by subversion (string)
     @param may_save flag indicating, that subversion is willing to save
         the answers returned (boolean)
     @return tuple of four values (retcode, username, password, save).
         Retcode should be True, if username and password should be used
         by subversion, username and password contain the relevant data
         as strings and save is a flag indicating, that username and
         password should be saved.
     """
     from .SvnLoginDialog import SvnLoginDialog
     cursor = QApplication.overrideCursor()
     if cursor is not None:
         QApplication.restoreOverrideCursor()
     parent = isinstance(self, QWidget) and self or None
     dlg = SvnLoginDialog(realm, username, may_save, parent)
     res = dlg.exec_()
     if cursor is not None:
         QApplication.setOverrideCursor(Qt.WaitCursor)
     if res == QDialog.Accepted:
         loginData = dlg.getData()
         return (True, loginData[0], loginData[1], loginData[2])
     else:
         return (False, "", "", False)
コード例 #7
0
ファイル: gui.py プロジェクト: jamesabel/latus
def main(latus_appdata_folder):

    latus.logger.log.info("latus_app_data: %s" % latus_appdata_folder)

    # check if we should run the setup wizard first
    if latus.preferences.preferences_db_exists(latus_appdata_folder):
        pref = latus.preferences.Preferences(latus_appdata_folder)
    else:
        pref = None

    app = QApplication(sys.argv)  # need this even for the GUIWizard

    if not pref or (pref and not pref.folders_are_set()):
        latus.logger.log.info('not all preferences are set - starting WizardGUI')
        app_gui_wizard = latus.gui_wizard.GUIWizard(latus_appdata_folder)
        app_gui_wizard.exec_()
        pref = latus.preferences.Preferences(latus_appdata_folder)

    if pref and pref.folders_are_set():
        app.setQuitOnLastWindowClosed(False)  # so popup dialogs don't close the system tray icon
        system_tray = LatusSystemTrayIcon(app, latus_appdata_folder)
        system_tray.start_latus()
        system_tray.show()
        app.exec_()
    else:
        msg = 'Incomplete configuration.\n\nPlease re-run Latus and complete the Latus Setup Wizard.\n\nExiting ...'
        mb = message_box(msg)
        mb.exec()
        latus.logger.log.warn(msg.replace('\n', ' '))  # don't put newlines in the log
        sys.exit(1)
コード例 #8
0
ファイル: main.py プロジェクト: dangmai/looper
def main():
    """
    Main function for the program
    """
    parser = argparse.ArgumentParser(
        description="Loop a video between 2 points in time based on rules in "
                    "a text file."
    )
    parser.add_argument('timestamp_filename', metavar='F', nargs='?',
                        help='the location of the timestamp file')
    parser.add_argument('--video_filename', metavar='V',
                        help='the location of the video file')
    args = parser.parse_args()
    app = QApplication(sys.argv)
    with open("gui/application.qss", "r") as theme_file:
        app.setStyleSheet(theme_file.read())
    main_window = MainWindow()

    if args.timestamp_filename:
        timestamp_filename = os.path.abspath(args.timestamp_filename)
        main_window.set_timestamp_filename(timestamp_filename)
    if args.video_filename:
        video_filename = os.path.abspath(args.video_filename)
        main_window.set_video_filename(video_filename)

    sys.exit(app.exec_())
コード例 #9
0
ファイル: SvnDiffDialog.py プロジェクト: paulmadore/Eric-IDE
 def __finish(self):
     """
     Private slot called when the user pressed the button.
     """
     QApplication.restoreOverrideCursor()
     
     self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
     self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
     
     tc = self.contents.textCursor()
     tc.movePosition(QTextCursor.Start)
     self.contents.setTextCursor(tc)
     self.contents.ensureCursorVisible()
     
     self.filesCombo.addItem(self.tr("<Start>"), 0)
     self.filesCombo.addItem(self.tr("<End>"), -1)
     for oldFile, newFile, pos in sorted(self.__fileSeparators):
         if oldFile != newFile:
             self.filesCombo.addItem(
                 "{0}\n{1}".format(oldFile, newFile), pos)
         else:
             self.filesCombo.addItem(oldFile, pos)
     
     self._cancel()
コード例 #10
0
ファイル: app.py プロジェクト: jrdbnntt/soap
class App(object):

    def __init__(self):
        self.settings = SettingsManager()
        self.app = QApplication([])
        self.gui = MainWindow(app=self)
        self.setup()

    def setup(self):
        self.gui.show()
        self.gui.resize(self.settings.get('application_width_initial'),
                        self.settings.get('application_height_initial'))

    def open(self):
        self.app.exec_()

    def suspend(self):
        pass

    def close(self):
        self.exit()

    def exit(self):
        """ Runs cleanup and then closes the app """
        self.app.exit()
        sys.exit()
コード例 #11
0
ファイル: findfiles.py プロジェクト: death-finger/Scripts
    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles
コード例 #12
0
ファイル: app.py プロジェクト: Cloudmage/mu
def run():
    """
    Creates all the top-level assets for the application, sets things up and
    then runs the application.
    """
    setup_logging()
    logging.info('Starting Mu {}'.format(__version__))
    # The app object is the application running on your computer.
    app = QApplication(sys.argv)
    # Display a friendly "splash" icon.
    splash = QSplashScreen(load_pixmap('icon'))
    splash.show()
    # Create the "window" we'll be looking at.
    editor_window = Window()
    # Create the "editor" that'll control the "window".
    editor = Editor(view=editor_window)
    # Setup the window.
    editor_window.closeEvent = editor.quit
    editor_window.setup(editor.theme)
    editor.restore_session()
    # Connect the various buttons in the window to the editor.
    button_bar = editor_window.button_bar
    button_bar.connect("new", editor.new, "Ctrl+N")
    button_bar.connect("load", editor.load, "Ctrl+O")
    button_bar.connect("save", editor.save, "Ctrl+S")
    button_bar.connect("flash", editor.flash)
    button_bar.connect("repl", editor.toggle_repl)
    button_bar.connect("zoom-in", editor.zoom_in)
    button_bar.connect("zoom-out", editor.zoom_out)
    button_bar.connect("theme", editor.toggle_theme)
    button_bar.connect("quit", editor.quit)
    # Finished starting up the application, so hide the splash icon.
    splash.finish(editor_window)
    # Stop the program after the application finishes executing.
    sys.exit(app.exec_())
コード例 #13
0
def QVTKRenderWidgetConeExample():
    """A simple example that uses the QVTKRenderWindowInteractor class."""

    # every QT app needs an app
    app = QApplication(['QVTKRenderWindowInteractor'])

    # create the widget
    widget = QVTKRenderWindowInteractor()
    widget.Initialize()
    widget.Start()
    # if you dont want the 'q' key to exit comment this.
    widget.AddObserver("ExitEvent", lambda o, e, a=app: a.quit())

    ren = vtk.vtkRenderer()
    widget.GetRenderWindow().AddRenderer(ren)

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)

    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())

    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)

    ren.AddActor(coneActor)

    # show the widget
    widget.show()
    # start event processing
    app.exec_()
コード例 #14
0
ファイル: earlyinit.py プロジェクト: B0073D/qutebrowser
def _die(message, exception=None):
    """Display an error message using Qt and quit.

    We import the imports here as we want to do other stuff before the imports.

    Args:
        message: The message to display.
        exception: The exception object if we're handling an exception.
    """
    from PyQt5.QtWidgets import QApplication, QMessageBox
    from PyQt5.QtCore import Qt

    if ("--debug" in sys.argv or "--no-err-windows" in sys.argv) and exception is not None:
        print(file=sys.stderr)
        traceback.print_exc()
    app = QApplication(sys.argv)
    if "--no-err-windows" in sys.argv:
        print(message, file=sys.stderr)
        print("Exiting because of --no-err-windows.", file=sys.stderr)
    else:
        message += "<br/><br/><br/><b>Error:</b><br/>{}".format(exception)
        msgbox = QMessageBox(QMessageBox.Critical, "qutebrowser: Fatal error!", message)
        msgbox.setTextFormat(Qt.RichText)
        msgbox.resize(msgbox.sizeHint())
        msgbox.exec_()
    app.quit()
    sys.exit(1)
コード例 #15
0
ファイル: __init__.py プロジェクト: AlexSchr/frescobaldi
def pixmap(name, size, mode, state):
    """Returns a (possibly cached) pixmap of the name and size with the default text color.
    
    The state argument is ignored for now.
    
    """
    if mode == QIcon.Selected:
        color = QApplication.palette().highlightedText().color()
    else:
        color = QApplication.palette().text().color()
    key = (name, size.width(), size.height(), color.rgb(), mode)
    try:
        return _pixmaps[key]
    except KeyError:
        i = QImage(size, QImage.Format_ARGB32_Premultiplied)
        i.fill(0)
        painter = QPainter(i)
        # render SVG symbol
        QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter)
        # recolor to text color
        painter.setCompositionMode(QPainter.CompositionMode_SourceIn)
        painter.fillRect(i.rect(), color)
        painter.end()
        # let style alter the drawing based on mode, and create QPixmap
        pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption())
        _pixmaps[key] = pixmap
        return pixmap
コード例 #16
0
 def __compileSelectedInterfaces(self):
     """
     Private method to compile selected interfaces to python.
     """
     if self.omniidl is not None:
         items = self.getSelectedItems()
         
         files = [self.project.getRelativePath(itm.fileName())
                  for itm in items]
         numIDLs = len(files)
         progress = E5ProgressDialog(
             self.tr("Compiling interfaces..."),
             self.tr("Abort"), 0, numIDLs,
             self.tr("%v/%m Interfaces"), self)
         progress.setModal(True)
         progress.setMinimumDuration(0)
         progress.setWindowTitle(self.tr("Interfaces"))
         i = 0
         
         for fn in files:
             progress.setValue(i)
             if progress.wasCanceled():
                 break
             proc = self.__compileIDL(fn, True, progress)
             if proc is not None:
                 while proc.state() == QProcess.Running:
                     QApplication.processEvents()
                     QThread.msleep(300)
                     QApplication.processEvents()
             else:
                 break
             i += 1
             
         progress.setValue(numIDLs)
コード例 #17
0
 def saveFileDialog(self):
     fname = self.filename()
     if fname == None:
         directory = "."
     else:
         directory = QFileInfo(fname).path()
     if util.isWindows():  # required for native looking file window
         fname = QFileDialog.getSaveFileName(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         self.writeDocumentToFile(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         fdialog.setAcceptMode(QFileDialog.AcceptSave)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.filesavedialog = fdialog
         self.filesavedialog.filesSelected.connect(
                                             self.saveFileDialogCallback)
         fdialog.open()
コード例 #18
0
ファイル: BackgroundService.py プロジェクト: Darriall/eric
 def restartService(self, language, forceKill=False):
     """
     Public method to restart a given lanuage.
     
     @param language to restart (str)
     @keyparam forceKill flag to kill a running task (bool)
     """
     try:
         proc, interpreter = self.processes.pop(language)
     except KeyError:
         return
     
     # Don't kill a process if it's still working
     if not forceKill:
         while self.isWorking is not None:
             QApplication.processEvents()
     
     conn = self.connections.pop(language, None)
     if conn:
         conn.blockSignals(True)
         conn.close()
     if proc:
         proc.close()
     
     port = self.serverPort()
     process = self.__startExternalClient(interpreter, port)
     if process:
         self.processes[language] = process, interpreter
コード例 #19
0
 def __compileAllInterfaces(self):
     """
     Private method to compile all interfaces to python.
     """
     if self.omniidl is not None:
         numIDLs = len(self.project.pdata["INTERFACES"])
         progress = E5ProgressDialog(
             self.tr("Compiling interfaces..."),
             self.tr("Abort"), 0, numIDLs,
             self.tr("%v/%m Interfaces"), self)
         progress.setModal(True)
         progress.setMinimumDuration(0)
         progress.setWindowTitle(self.tr("Interfaces"))
         i = 0
         
         for fn in self.project.pdata["INTERFACES"]:
             progress.setValue(i)
             if progress.wasCanceled():
                 break
             proc = self.__compileIDL(fn, True, progress)
             if proc is not None:
                 while proc.state() == QProcess.Running:
                     QApplication.processEvents()
                     QThread.msleep(300)
                     QApplication.processEvents()
             else:
                 break
             i += 1
         
         progress.setValue(numIDLs)
コード例 #20
0
ファイル: treeview.py プロジェクト: TresysTechnology/setools
    def copy_tree(self):
        """Copy the tree to the clipboard."""

        items = []
        inval_index = QModelIndex()
        it = QTreeWidgetItemIterator(self)
        prev_depth = 0
        while it.value():
            depth = 0
            item = it.value()
            parent = item.parent()
            while parent:
                depth += 1
                parent = parent.parent()

            if depth < prev_depth:
                items.extend(["  |"*depth, "\n"])

            if depth:
                items.extend(["  |"*depth, "--", item.text(0), "\n"])
            else:
                items.extend([item.text(0), "\n"])

            prev_depth = depth
            it += 1

        QApplication.clipboard().setText("".join(items))
コード例 #21
0
 def _copy_nodeid(self):
     node = self.get_current_node()
     if node:
         text = node.nodeid.to_string()
     else:
         text = ""
     QApplication.clipboard().setText(text)
コード例 #22
0
    def test_receive(self):
        port = self.__get_free_port()
        receive_dialog = self.__get_recv_dialog()
        receive_dialog.device.set_server_port(port)
        receive_dialog.ui.btnStart.click()

        data = np.array([complex(1, 2), complex(3, 4), complex(5, 6)], dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertEqual(receive_dialog.device.current_index, 3)
        self.assertTrue(np.array_equal(receive_dialog.device.data[:3], data))

        receive_dialog.ui.btnStop.click()
        receive_dialog.ui.btnClear.click()

        self.assertEqual(receive_dialog.device.current_index, 0)

        self.__close_dialog(receive_dialog)
コード例 #23
0
    def test_spectrum(self):
        port = self.__get_free_port()
        spectrum_dialog = self.__get_spectrum_dialog()
        spectrum_dialog.device.set_server_port(port)
        spectrum_dialog.ui.btnStart.click()
        self.assertEqual(len(spectrum_dialog.scene_manager.peak), 0)

        data = np.array([complex(1, 1), complex(2, 2), complex(3, 3)], dtype=np.complex64)

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        sock.connect(("127.0.0.1", port))
        sock.sendall(data.tostring())
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()

        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertGreater(len(spectrum_dialog.scene_manager.peak), 0)

        spectrum_dialog.ui.btnStop.click()

        self.__close_dialog(spectrum_dialog)
コード例 #24
0
ファイル: app.py プロジェクト: farlandliu/FeelUOwn
    def __init__(self):
        super().__init__()
        self.player = Player(self)
        self.player_mode_manager = PlayerModeManager(self)
        self.request = Request(self)
        self.server = Server(self)
        self.theme_manager = ThemeManager(self)
        self.tips_manager = TipsManager(self)
        self.hotkey_manager = Hotkey(self)
        self.plugins_manager = PluginsManager(self)
        self.version_manager = VersionManager(self)
        self.theme_manager.set_theme(DEFAULT_THEME_NAME)

        self.ui = Ui(self)
        self._init_managers()

        self.player_pixmap = None

        self.resize(960, 600)
        self.setObjectName('app')
        QApplication.setWindowIcon(QIcon(APP_ICON))
        self.set_theme_style()

        self.bind_signal()
        self.test()
コード例 #25
0
ファイル: vacap.py プロジェクト: juancarlospaco/vacap
 def make_zip(self):
     """Try to make a ZIP file."""
     try:
         # iterate over lists of folders to backup
         for folder_to_backup in self.origins:
             percentage = int(self.origins.index(folder_to_backup) /
                              len(self.origins) * 100)
             self.setLabelText(self.template.format(
                 folder_to_backup[:99], self.destination.lower()[:99],
                 self._date, datetime.now().isoformat()[:-7],
                 self.seconds_time_to_human_str(time.time() - self._time),
                 len(self.origins) - self.origins.index(folder_to_backup),
                 percentage))
             self.setValue(percentage)
             QApplication.processEvents()  # Forces the UI to Update
             log.info("Folder to backup: {}.".format(folder_to_backup))
             shutil.make_archive(folder_to_backup, "zip",
                                 folder_to_backup, logger=log)
             self.move_zip(folder_to_backup + ".zip")
     except Exception as reason:
         log.warning(reason)
     else:
         log.info("Copia de Seguridad Backup Termino bien.")
     finally:
         log.info("Finished BackUp from {} to {}.".format(
             self.origins, self.destination))
コード例 #26
0
ファイル: HelpSearchWidget.py プロジェクト: pycom/EricShort
 def __searchingFinished(self, hits):
     """
     Private slot to handle the end of the search.
     
     @param hits number of hits (integer) (unused)
     """
     QApplication.restoreOverrideCursor()
コード例 #27
0
ファイル: fontWindow.py プロジェクト: madig/trufont
 def openFile(self):
     path, _ = QFileDialog.getOpenFileName(
         self, self.tr("Open File"), '',
         platformSpecific.fileFormat
     )
     if path:
         QApplication.instance().openFile(path)
コード例 #28
0
    def test_send(self):
        port = self.__get_free_port()
        receive_dialog = self.__get_recv_dialog()
        receive_dialog.device.set_server_port(port)
        receive_dialog.ui.btnStart.click()

        send_dialog = self.__get_send_dialog()
        send_dialog.device.set_client_port(port)
        send_dialog.ui.spinBoxNRepeat.setValue(2)
        send_dialog.ui.btnStart.click()
        QApplication.instance().processEvents()
        QTest.qWait(self.SEND_RECV_TIMEOUT)

        self.assertEqual(receive_dialog.device.current_index, 2 * self.signal.num_samples)
        self.assertTrue(np.array_equal(receive_dialog.device.data[:receive_dialog.device.current_index // 2],
                                       self.signal.data))

        self.assertEqual(send_dialog.send_indicator.rect().width(), self.signal.num_samples)
        self.assertFalse(send_dialog.ui.btnClear.isEnabled())

        send_dialog.on_clear_clicked()
        self.assertEqual(send_dialog.send_indicator.rect().width(), 0)
        send_dialog.ui.btnStop.click()
        self.assertFalse(send_dialog.ui.btnStop.isEnabled())
        receive_dialog.ui.btnStop.click()
        self.assertFalse(receive_dialog.ui.btnStop.isEnabled())

        self.__close_dialog(receive_dialog)
        self.__close_dialog(send_dialog)
コード例 #29
0
def main(args):
    app = QApplication([])

    main_frame = QFrame()

    layout = QVBoxLayout(main_frame)

    number_edit = PyQtExtras.NumberEdit()
    number_edit.set_value(10)
    print "Current value of 1 is: " + str(number_edit.get_value())

    number_edit2 = PyQtExtras.NumberEdit(max_length=2)
    number_edit2.set_value(2)
    print "Current value of 2 is: " + str(number_edit2.get_value())
    number_edit2.set_value(20)
    print "Current value of 2 is: " + str(number_edit2.get_value())

    number_edit3 = PyQtExtras.NumberEdit(max_length=1)
    number_edit3.set_value(2)
    print "Current value of 3 is: " + str(number_edit3.get_value())
    number_edit3.set_value(50)
    print "Current values of 3 is: " + str(number_edit3.get_value())
    number_edit3.set_value(25)
    print "Current value of 3 is: " + str(number_edit3.get_value())
    number_edit3.set_value("text")
    print "Current value of 3 is: " + str(number_edit3.get_value())

    layout.addWidget(number_edit)
    layout.addWidget(number_edit2)
    layout.addWidget(number_edit3)

    main_frame.show()

    app.exec_()
コード例 #30
0
 def __finish(self):
     """
     Private slot called when the process finished or the user pressed
     the button.
     """
     QApplication.restoreOverrideCursor()
     
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
     self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)
     
     self.refreshButton.setEnabled(True)
     self.__updateButtons()
     self.__updateCommitButton()
     
     self.__statusFilters.sort()
     self.__statusFilters.insert(0, "<{0}>".format(self.tr("all")))
     self.statusFilterCombo.addItems(self.__statusFilters)
     
     for act in self.menuactions:
         act.setEnabled(True)
     
     self.__resizeColumns()
     self.__resort()
     
     self._cancel()
コード例 #31
0
ファイル: controller.py プロジェクト: pacas/PMMP_Stellaris
                if os.path.exists(disk.device + self.steam) is True:
                    self.steam = disk.device + self.steam
                    self.check = 1
                    break
        except Exception as err:
            self.logs.error(err, exc_info=True)
    
    def set_Game_Location_MM(self):
        try:
            self.steamMM = self.gamepath[:self.gamepath.find('steamapps') + 10] + 'workshop/content/281990/'
        except Exception:
            self.steamMM = ''

    def ini_Write(self, path, lang):
        try:
            with open(pth.ini_file, 'w+', encoding='UTF-8') as settings:
                settings.write('game_location=' + path + '\nlang=' + lang)
        except FileNotFoundError:
            print("\a")
            QMessageBox.about(self, "Warning", "Error")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    Controller = Controller()
    # --------Design options------------
    app.setStyle('Fusion')
    app.setStyleSheet(style.main_design)
    # --------Final close func----------
    sys.exit(app.exec())
コード例 #32
0
ファイル: ExempleQt.py プロジェクト: julienGautier77/utils
        self.data=np.random.rand(350, 400)
        self.imh.setImage(self.data)
        
        hMainLayout.addLayout(self.vbox2)
        
        
        self.setLayout(hMainLayout)  # 
    
    def ActionButton(self): # definition de ce qui se passe quand tu clique
        self.box3.editingFinished.connect(self.Actionbox)
        self.Button1.clicked.connect(self.ActionButton1)
        self.checkBox1.stateChanged.connect(self.ActionCheckBox1)
        
    def Actionbox(self):
        print('box', self.box3.value())
    
    def ActionButton1(self):
        print('action button1')
        
    def ActionCheckBox1(self):
        print('action')
        
if __name__ == "__main__":
    
    appli = QApplication(sys.argv) 
    #appli.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) Si tu veux en noir 
    e = WIND()
    e.show()
    appli.exec_()     
        
        
コード例 #33
0
ファイル: GUI.py プロジェクト: aheyeant/ACO_visualization
                            node.y * PIXEL_SIZE,
                            PIXEL_SIZE,
                            PIXEL_SIZE)
            qp.setPen(START_COLOR)
            qp.setBrush(QBrush(START_COLOR))
            qp.drawRect(self._communicator.draw_place.start.x * PIXEL_SIZE,
                        self._communicator.draw_place.start.y * PIXEL_SIZE,
                        PIXEL_SIZE,
                        PIXEL_SIZE)
            qp.setBrush(brush)

    def closeEvent(self, e):
        self._aco.stop()
        super().closeEvent(e)

    def paintEvent(self, e):
        qp = QPainter()
        qp.begin(self)
        self._draw(qp)
        qp.end()

    def moveEvent(self, e):
        super().moveEvent(e)


if __name__ == "__main__":

    app = QApplication(sys.argv)
    gui = GUI()
    sys.exit(app.exec_())
コード例 #34
0
 def on_cell_clicked(self, r, c):
     txt = self.table_widget.cellWidget(r,c).text()
     clipboard = QApplication.instance().clipboard()
     clipboard.setText(txt)
コード例 #35
0
def application():
    app = QApplication(sys.argv)
    main_window = MainWindow()

    main_window.show()
    sys.exit(app.exec_())
コード例 #36
0
 def setUpClass(cls):
     app = QApplication(sys.argv)
     cls.widget = InvoiceX()
     cls.widget.fileName = ['../invoice.pdf']
     cls.widget.load_pdf_file()
コード例 #37
0
ファイル: 02_Linear_layout.py プロジェクト: Sumsum99/GUI_PyQt
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel

if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = QWidget()
    window.resize(500, 500)

    layout = QHBoxLayout(window) # 순차적으로 쌓아주는 방법 (수평방향)
    window.setLayout(layout) # 레이아웃이 기본 위젯에 셋팅됨

    label1 = QLabel("label1", window)
    label2 = QLabel("label2", window)
    label3 = QLabel("label3", window)

    label1.setStyleSheet("background-color:red")
    label2.setStyleSheet("background-color:orange")
    label3.setStyleSheet("background-color:yellow")

    layout.addWidget(label1)
    layout.addWidget(label2)
    layout.addWidget(label3)

    window.show()

    app.exec_()
コード例 #38
0
            i.setEnabled(locked)

    def OnUpdate(self, delta):
        b = self.checkBox.isChecked()
        self.checkBox.setText('→' if b else '↓')
        for i in self.grid:
            for j in i:
                j.setProperty('selected', False)
        for i in range(self.wordLen.value()):
            if b:
                if self.wordX.value() + i < 16:
                    self.grid[self.wordX.value() + i][self.wordY.value()].setProperty('selected', True)
            else:
                if self.wordY.value() + i < 16:
                    self.grid[self.wordX.value()][self.wordY.value() + i].setProperty('selected', True)
        self.setStyleSheet(self.stylesheet)

    def closeEvent(self, e):
        self.board.close()
        Game.closeEvent(self, e)

    def getName(self):
        return 'WordMaker'


if __name__ == '__main__':
    a = QApplication(sys.argv)
    ex = WordMaker(None)
    ex.show()
    sys.exit(a.exec_())
コード例 #39
0
 def loadStartedHandler(self):
     """Set waiting cursor when the page is loading"""
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
コード例 #40
0
ファイル: utils.py プロジェクト: BaptPicxDev/music-classif
def get_DPI():
    app = QApplication(sys.argv)
    screen = app.screens()[0]
    dpi = screen.physicalDotsPerInch()
    app.quit()
    return dpi
コード例 #41
0
        starting_dir = os.path.expanduser("~")
        if self._fullPathOutputSlot.ready():
            starting_dir = os.path.split(self._fullPathOutputSlot.value)[0]

        dlg = QFileDialog(self, "Export Location", starting_dir,
                          self._file_filter)
        dlg.setDefaultSuffix(self._extension)
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        if not dlg.exec_():
            return

        exportPath = dlg.selectedFiles()[0]
        self._filepathSlot.setValue(exportPath)
        self.filepathEdit.setText(exportPath)


if __name__ == "__main__":
    from PyQt5.QtWidgets import QApplication
    from lazyflow.graph import Graph
    from lazyflow.operators.ioOperators import OpNpyWriter

    op = OpNpyWriter(graph=Graph())

    app = QApplication([])
    w = SingleFileExportOptionsWidget(None, "npy", "numpy files (*.npy)")
    w.initSlot(op.Filepath)
    w.show()
    app.exec_()

    print("Selected Filepath: {}".format(op.Filepath.value))
コード例 #42
0
 def loadFinishedHandler(self, *args, **kwargs):
     """Recover cursor when done"""
     self.progress.setStyleSheet("background-color:#263044;")
     QApplication.restoreOverrideCursor()
コード例 #43
0
ファイル: spreadsheet.py プロジェクト: gucxufangling/pychemqt
class Spreadsheet(equipment):
    """Clase que define un la interaccion con un hoja de calculo de
    libreoffice/openoffice

    Parámetros:
        project: instancia project
        input: entity de entrada
        output: entity de salida
        filename: Path del archivo ods
        datamap: Array con la estructura de datos a traspasar, cada elemento
        es un dicciontario con los datos de conversion de valores
                entity: corriente o equipo del que exportar el valor
                variable: nombre del valor de la variable de la corriente
                unidad: unidad del valor a pasar en el caso de magitudes
                hoja: Nombre de la hoja
                celda: Celda en la que colocar el dato

    """
    title = QApplication.translate("pychemqt", "Spreadsheet")
    help = ""
    kwargs = {
        "project": None,
        "input": "",
        "output": "",
        "filename": "",
        "datamap": []}
    kwargs_forbidden = ["project", ]

    @property
    def isCalculable(self):
        self.msg = ""
        self.status = 1
        if not self.kwargs["filename"] or \
                not os.path.isfile(self.kwargs["filename"]):
            self.msg = QApplication.translate(
                "pychemqt", "undefined spreadsheet filename")
            self.status = 0
            return
        if not self.kwargs["datamap"]:
            self.msg = QApplication.translate(
                "pychemqt", "undefined spreadsheet data map")
            self.status = 3
        return True

    def cleanOldValues(self, **kwargs):
        """Si se cambia la ruta de la hoja de cálculo se reinicia el datamap"""
        if kwargs.get("filename", "") and \
                kwargs.get("filename", "") != self.kwargs["filename"]:
            self.kwargs["datamap"] = []
        self.kwargs.update(kwargs)

    def calculo(self):
        ext = self.kwargs["filename"].split(".")[-1]
        if ext == "ods":
            self._dependence = "ezodf"
            spreadsheet = ezodf.opendoc(self.kwargs["filename"])
            self.sheets = [name for name in spreadsheet.sheets.names()]
            if self.kwargs["datamap"]:
                for data in self.kwargs["datamap"]:
                    entity = self.kwargs["project"].getObject(data["entity"])
                    sheet = spreadsheet.sheets[data["sheet"]]
                    indProp = entity.propertiesTitle().index(data["property"])
                    if entity.propertiesUnit()[indProp] == str:
                        value = entity.__getattribute__(
                            entity.propertiesAttribute()[indProp])
                    else:
                        indUnit = entity.propertiesUnit()[indProp].__text__.index(data["unit"])
                        units = entity.propertiesUnit()[indProp].__units__
                        value = entity.__getattribute__(entity.propertiesAttribute()[indProp]).__getattribute__(units[indUnit])

                    # Chequear
                    celda = list(data["cell"])
                    column = []
                    while celda[0] in string.ascii_uppercase:
                        column.append(celda.pop(0))
                    base = len(string.ascii_uppercase)
                    exponente = 0
                    columna = 0
                    while column:
                        ordinal = ord(column.pop())-64
                        columna += ordinal*base**exponente
                        exponente += 1
                    fila = int("".join(celda))
                    if fila > sheet.nrows():
                        sheet.append_rows(fila-sheet.nrows())
                    if columna > sheet.ncols():
                        sheet.append_columns(columna-sheet.ncols())

                    sheet[data["cell"]].set_value(value)
                spreadsheet.save()

        elif ext == "xlsx":
            self._dependence = "openpyxl"
            spreadsheet = openpyxl.load_workbook(self.kwargs["filename"])
            self.sheets = spreadsheet.get_sheet_names()
            if self.kwargs["datamap"]:
                for data in self.kwargs["datamap"]:
                    entity = self.kwargs["project"].getObject(data["entity"])
                    sheet = spreadsheet[data["sheet"]]
                    indProp = entity.propertiesTitle().index(data["property"])
                    if entity.propertiesUnit()[indProp] == str:
                        value = entity.__getattribute__(entity.propertiesAttribute()[indProp])
                    else:
                        indUnit = entity.propertiesUnit()[indProp].__text__.index(data["unit"])
                        units = entity.propertiesUnit()[indProp].__units__
                        value = entity.__getattribute__(entity.propertiesAttribute()[indProp]).__getattribute__(units[indUnit])
                    sheet[data["cell"]] = value
                    comentario = openpyxl.comments.Comment("{0[entity]}.{0[property]}.{0[unit]} ---> {0[sheet]}.{0[cell]}".format(data), 'pychemqt')
                    sheet[data["cell"]].comment = comentario
                spreadsheet.save(".".join(self.kwargs["filename"].split(".")[:-1])+"-bak"+".xlsx")

            elif ext == "xls":
                # TODO: Implement old office support
                pass

        self.salida = []

    def writeListtoJSON(self, kwarg, key, value):
        """Personalizar en el caso de equipos con listas complejas"""
        kwarg_list = {}
        if key == "datamap":
            for i, data in enumerate(value):
                kwarg_list[i] = data
        kwarg[key] = kwarg_list

    def readListFromJSON(self, data, key):
        """Read list from file, customize in entities with complex list"""
        kwarg = []
        if key == "datamap":
            for i, data in data[key].items():
                kwarg.append(data)
        return kwarg

    def propTxt(self):
        txt = "#---------------"
        txt += QApplication.translate("pychemqt", "Data map")
        txt += "-----------------#" + os.linesep
        txt += self.propertiesToText(0)
        if self.kwargs["datamap"]:
            for data in self.kwargs["datamap"]:
                txt += "{0[entity]}.{0[property]}.{0[unit]} ---> {0[sheet]}.{0[cell]}".format(data)+os.linesep
        else:
            txt += QApplication.translate("pychemqt", "Undefined")+os.linesep

        return txt

    @classmethod
    def propertiesEquipment(cls):
        l = [(QApplication.translate("pychemqt", "Spreadsheet path"),
              "filename", str),
             (QApplication.translate("pychemqt", "Data map"), "datamap", None)]
        return l

    def propertiesListTitle(self, index):
        lista = []
        for data in self.kwargs["datamap"]:
            lista.append("{0[entity]}.{0[property]}.{0[unit]} ---> {0[sheet]}.{0[cell]}".format(data))
        return lista

    def writeStatetoJSON(self, state):
        """Write instance parameter to file"""
        state["sheets"] = self.sheets

    def readStatefromJSON(self, state):
        """Load instance parameter from saved file"""
        self.sheets = state["sheets"]
        self.salida = [None]
コード例 #44
0
        self.setGeometry(300, 300, 250, 200)
        self.setWindowTitle("Delegate")
       
        self.initData()
        self.initUI()
        

    def initData(self):
            
        vals = ["0", "1", "2", "3", "4"]
        
        self.model = QStringListModel(vals)
        
        
    def initUI(self):
    
        lv = QListView(self)
        lv.setModel(self.model)
        
        self.de = MyDelegate()
        lv.setItemDelegate(self.de)
        
        layout = QVBoxLayout()
        layout.addWidget(lv) 
        self.setLayout(layout) 
       

app = QApplication([])
ex = Example()
ex.show()
sys.exit(app.exec_())
コード例 #45
0
        self.x = 0
        self.y = 0

    def up(self):
        self.x += 10
        self.y -= 10
        print(self.x)
        print(self.y)

    def down(self):
        self.x -= 10
        self.y += 10
        print(self.x)
        print(self.y)

    def paintEvent(self, event):
        backPosX = 200
        backPosY = 200
        pixmap = QPixmap("back.png")
        painter = QPainter(self)
        painter.drawPixmap(QtCore.QRect(backPosX,backPosY,pixmap.width(),pixmap.height()), pixmap)
        pen = QPen(Qt.red, 3)
        painter.setPen(pen)
        painter.drawLine(backPosX+pixmap.width()//2-5, backPosY+pixmap.height()//2, 210+self.x,backPosY+pixmap.height()//2+self.y)

app = QApplication(argv)
window = Ui()
window.show()
app.exec_()
コード例 #46
0
ファイル: printdialog.py プロジェクト: lostb1d/pyqt5

    def exitWindow(self):
        self.close()

    def createEditor(self):
        self.textEdit = QTextEdit(self)
        self.setCentralWidget(self.textEdit)

    def fontDialof(self):
        font, ok = QFontDialog.getFont()

        if ok:
            self.textEdit.setFont(font)

    def colorDialog(self):
        color = QColorDialog.getColor()
        self.textEdit.setTextColor(color)

    def printDialog(self):
        printer = QPrinter(QPrinter.HighResolution)
        dialog = QPrintDialog(printer, self)

        if dialog.exec() == QPrintDialog.Accepted:
            self.textEdit.print_(printer)


if __name__ == "__main__":
    App = QApplication(sys.argv)
    window = Window()
    sys.exit(App.exec())
コード例 #47
0
    print('widget.width()=%d' % widget.width())
    print('widget.height()=%d' % widget.height())

    print('2')
    print('widget.geometry().x()=%d' % widget.geometry().x())
    print('widget.geometry().y()=%d' % widget.geometry().y())
    print('widget.geometry().width()=%d' % widget.geometry().width())
    print('widget.geometry().height()=%d' % widget.geometry().height())

    print('3')
    print('widget.frameGeometry().x()=%d' % widget.frameGeometry().x())
    print('widget.frameGeometry().y()=%d' % widget.frameGeometry().y())
    print('widget.frameGeometry().width()=%d' % widget.frameGeometry().width())
    print('widget.frameGeometry().height()=%d' % widget.frameGeometry().height())

app=QApplication(sys.argv)  #创建一个应用
widget=QWidget()            #创建一个窗口
btn=QPushButton(widget)     #创建一个按钮,继承widget的类
btn.setText('按钮')         #设置button的文字
btn.move(24,52)             #设置button的位置
btn.clicked.connect(on_Click) #建立槽与信号的关联
widget.resize(300,240)      #设置窗口的大小
widget.move(250,200)
widget.setWindowTitle('屏幕坐标系')
widget.show()               #使窗口显示
sys.exit(app.exec_())       #完美退出




コード例 #48
0
ファイル: spreadsheet.py プロジェクト: gucxufangling/pychemqt
 def propertiesEquipment(cls):
     l = [(QApplication.translate("pychemqt", "Spreadsheet path"),
           "filename", str),
          (QApplication.translate("pychemqt", "Data map"), "datamap", None)]
     return l
コード例 #49
0
ファイル: ej30.py プロジェクト: ChrisLe7/ISSBC
def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
コード例 #50
0
# GUI boxes that display over the game

print('Starting :)')

class boxWindow(QMainWindow):
    def __init__(self, x, y):
        QMainWindow.__init__(self)
        self.setWindowFlags(
            QtCore.Qt.WindowStaysOnTopHint |
            QtCore.Qt.FramelessWindowHint |
            QtCore.Qt.X11BypassWindowManagerHint
        )
        self.setGeometry(x + 60, y + 60, 50, 50)


app = QApplication(sys.argv)

windows = [None] * 4

for i in range(4):
    windows[i] = boxWindow(0, 0)


def clearWindows():
    for i in range(4):
        windows[i].close()


########################################################################################################################
# Loading images needed for the program
コード例 #51
0
 def setUpClass(cls):
     """Create QApplication"""
     try:
         cls.app = QApplication(sys.argv)
     except:
         pass
コード例 #52
0
        self.setLayout(HLayout)
        
        
        
    def Display(self,data,autoLevels=True,color='flame'):  
        self.imh.setImage(data.astype(float),autoLevels=autoLevels,autoDownsample=True)
        self.hist.gradient.loadPreset(color)
        
    def SetTITLE(self,title):
        self.setWindowTitle(title)
        
    def showFullScree(self):
        self.showMaximized()  
        
    def closeEvent(self, event):
        """ when closing the window
        """
        self.isWinOpen=False
        time.sleep(0.1)
        event.accept()
    
        
    
if __name__ == "__main__":
    appli = QApplication(sys.argv) 
    appli.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    e = FULLSCREEN() 
    e.show()
    appli.exec_()     
        
コード例 #53
0
 def copy_text(self):
     cb = QApplication.clipboard()
     cb.clear(mode=cb.Clipboard)
     cb.setText(self.log_text.toPlainText(), mode=cb.Clipboard)
コード例 #54
0
			margin:0px;

		}
		QLabel{
			font-weight:bold;
			background-color:transparent;
			font-size: 18px;	
		}
		#QLabel{
			font-weight:Normal;
			background-color:transparent;
			font-size: 14px;	
		}
		QLineEdit{
			padding:3px;
			margin:6px;
		}

		QCheckBox{
			margin:6px;
		}
		"""
		return(css)
		#def _define_css
#class runomatic

app=QApplication(["LliuWin Wizard"])
wizardLauncher=wizard()
app.exec_()

コード例 #55
0
    def tabopen(
            self,
            url: QUrl = None,
            background: bool = None,
            related: bool = True,
            idx: int = None,
            *,
            ignore_tabs_are_windows: bool = False) -> browsertab.AbstractTab:
        """Open a new tab with a given URL.

        Inner logic for open-tab and open-tab-bg.
        Also connect all the signals we need to _filter_signals.

        Args:
            url: The URL to open as QUrl or None for an empty tab.
            background: Whether to open the tab in the background.
                        if None, the `tabs.background` setting decides.
            related: Whether the tab was opened from another existing tab.
                     If this is set, the new position might be different. With
                     the default settings we handle it like Chromium does:
                         - Tabs from clicked links etc. are to the right of
                           the current (related=True).
                         - Explicitly opened tabs are at the very right
                           (related=False)
            idx: The index where the new tab should be opened.
            ignore_tabs_are_windows: If given, never open a new window, even
                                     with tabs.tabs_are_windows set.

        Return:
            The opened WebView instance.
        """
        if url is not None:
            qtutils.ensure_valid(url)
        log.webview.debug("Creating new tab with URL {}, background {}, "
                          "related {}, idx {}".format(url, background, related,
                                                      idx))

        prev_focus = QApplication.focusWidget()

        if (config.val.tabs.tabs_are_windows and self.widget.count() > 0
                and not ignore_tabs_are_windows):
            window = mainwindow.MainWindow(private=self.is_private)
            window.show()
            tabbed_browser = objreg.get('tabbed-browser',
                                        scope='window',
                                        window=window.win_id)
            return tabbed_browser.tabopen(url=url,
                                          background=background,
                                          related=related)

        tab = browsertab.create(win_id=self._win_id,
                                private=self.is_private,
                                parent=self.widget)
        self._connect_tab_signals(tab)

        if idx is None:
            idx = self._get_new_tab_idx(related)
        self.widget.insertTab(idx, tab, "")

        if url is not None:
            tab.load_url(url)

        if background is None:
            background = config.val.tabs.background
        if background:
            # Make sure the background tab has the correct initial size.
            # With a foreground tab, it's going to be resized correctly by the
            # layout anyways.
            tab.resize(self.widget.currentWidget().size())
            self.widget.tab_index_changed.emit(self.widget.currentIndex(),
                                               self.widget.count())
            # Refocus webview in case we lost it by spawning a bg tab
            self.widget.currentWidget().setFocus()
        else:
            self.widget.setCurrentWidget(tab)
            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-68076
            # Still seems to be needed with Qt 5.11.1
            tab.setFocus()

        mode = modeman.instance(self._win_id).mode
        if mode in [
                usertypes.KeyMode.command, usertypes.KeyMode.prompt,
                usertypes.KeyMode.yesno
        ]:
            # If we were in a command prompt, restore old focus
            # The above commands need to be run to switch tabs
            if prev_focus is not None:
                prev_focus.setFocus()

        tab.show()
        self.new_tab.emit(tab, idx)
        return tab
コード例 #56
0
ファイル: code_Location.py プロジェクト: trinkner/lapwing
    def html(self):

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # create start to basic html format
        html = """
            <!DOCTYPE html>
            <html>
            <head>
            </head>
            <style>
            * {
                font-size: 75%;
                font-family: "Times New Roman", Times, serif;
                }
            th {
                text-align: left;
            }
            </style>
            <body>
            """

        # add title information
        html = html + ("<H1>" + self.lblLocation.text() + "</H1>")

        html = html + ("<H3>" + self.lblFirstVisited.text() + "</H3>")

        html = html + ("<H3>" + self.lblMostRecentlyVisited.text() + "</H3>")

        # grab the map image from the map tap
        # process it into a byte array and encode it
        # so we can insert it inline into the html
        myPixmap = self.webMap.grab()
        myPixmap = myPixmap.scaledToWidth(600, Qt.SmoothTransformation)

        myByteArray = QByteArray()
        myBuffer = QBuffer(myByteArray)
        myBuffer.open(QIODevice.WriteOnly)
        myPixmap.save(myBuffer, "PNG")

        encodedImage = b64encode(myByteArray)

        html = html + ("""
        <img src="data:image/png;base64, 
        """)

        html = html + str(encodedImage)[1:]

        html = html + ("""        
        "  />
        """)

        html = html + ("<H4>" + "Species" "</H4>")

        html = html + ("<font size='2'>" + "<p>")

        # loopthrough the species listed in tblSpecies
        for r in range(self.tblSpecies.rowCount()):
            html = html + (self.tblSpecies.item(r, 1).text() + "<br>")

        html = html + ("<H4>" + "Dates" + "</H4>")

        # create filter set to our current location
        filter = code_Filter.Filter()
        filter.setLocationType = "Location"
        filter.setLocationName = self.lblLocation.text()

        # for each date in tblDates, find the species and display them in a table
        for r in range(self.tblDates.rowCount()):

            html = html + ("<b>" + self.tblDates.item(r, 1).text() + "</b>")

            filter.setStartDate(self.tblDates.item(r, 1).text())
            filter.setEndDate(self.tblDates.item(r, 1).text())
            species = self.mdiParent.db.GetSpecies(filter)

            html = html + ("<br>" "<table width='100%'>" "<tr>")

            # set up counter R to start a new row after listing each 3 species
            R = 1
            for s in species:
                html = html + ("<td>" + s + "</td>")
                if R == 3:
                    html = html + ("</tr>" "<tr>")
                    R = 0
                R = R + 1

            html = html + ("<br>" + "<br>" + "<br>" + "</table>")

        html = html + ("<font size>" + "</body>" + "</html>")

        QApplication.restoreOverrideCursor()

        return (html)
コード例 #57
0
def main():
    app = QApplication(sys.argv)

    w = MyWidget()
    sys.exit(app.exec_())
コード例 #58
0
ファイル: main.py プロジェクト: anglebinbin/Barista-tool
 parser.add_argument('-d',
                     '--dir',
                     help='local directory to run server sessions in',
                     type=str,
                     default='.')
 parser.add_argument('-o',
                     '--open',
                     help='path to a Barista project to be opened',
                     type=str,
                     default='')
 args = parser.parse_args()
 # Get caffepath out of settings.
 settings = applicationQSetting()
 settings.beginGroup("Path")
 path = settings.value("caffePath")
 app = QApplication(sys.argv)
 signal.signal(signal.SIGINT, signal.SIG_DFL)
 # Start local server on 'localhost:4200' in subprocess.
 if args.server:
     if not os.path.exists(args.dir):
         logging.error("Session folder '%s' does not exist." % (args.dir))
         sys.stderr.write("Session folder '%s' does not exist." %
                          (args.dir))
         exit(2)
     command = './server.py --port {} --dir {}'.format(
         BaristaServer.DEFAULT_PORT, args.dir)
     pid = subprocess.Popen(command.split()).pid
     # Stop the server when the app is about to quit.
     app.aboutToQuit.connect(lambda: os.kill(pid, signal.SIGTERM))
 # server = BaristaServer(app, ip=None, port=BaristaServer.DEFAULT_PORT, sessionPath='sessions')
 # Set global application stylesheet.
コード例 #59
0
def main():
    app = QApplication(sys.argv)
    dialogo = AplicacionGestorDescargas()

    sys.exit(app.exec_())
コード例 #60
0
ファイル: qt.py プロジェクト: Future-Cities-Lab/MurmurWall
from apscheduler.schedulers.qt import QtScheduler

try:
    from PyQt5.QtWidgets import QApplication, QLabel
except ImportError:
    try:
        from PyQt4.QtGui import QApplication, QLabel
    except ImportError:
        from PySide.QtGui import QApplication, QLabel


def tick():
    label.setText('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    signal.signal(signal.SIGINT, lambda *args: QApplication.quit())  # This enables processing of Ctrl+C keypresses
    label = QLabel('The timer text will appear here in a moment!')
    label.setWindowTitle('QtScheduler example')
    label.setFixedSize(280, 50)
    label.show()

    scheduler = QtScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.start()

    # Execution will block here until the user closes the windows or Ctrl+C is pressed.
    app.exec_()