Python qtpy.QtGui.QPixmap() Examples

The following are 29 code examples of qtpy.QtGui.QPixmap(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module qtpy.QtGui , or try the search function .
Example #1
Source File: restart.py    From tellurium with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        super(Restarter, self).__init__()
        self.ellipsis = ['', '.', '..', '...', '..', '.']

        # Widgets
        self.timer_ellipsis = QTimer(self)
        self.splash = QSplashScreen(QPixmap(get_image_path(
                                        'Tellurium_splash.png'), 'png'))

        # Widget setup
        self.setVisible(False)

        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()

        self.timer_ellipsis.timeout.connect(self.animate_ellipsis) 
Example #2
Source File: restart.py    From tellurium with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        super(Restarter, self).__init__()
        self.ellipsis = ['', '.', '..', '...', '..', '.']

        # Widgets
        self.timer_ellipsis = QTimer(self)
        self.splash = QSplashScreen(QPixmap(get_image_path(
                                        'Tellurium_splash.png'), 'png'))

        # Widget setup
        self.setVisible(False)

        font = self.splash.font()
        font.setPixelSize(10)
        self.splash.setFont(font)
        self.splash.show()

        self.timer_ellipsis.timeout.connect(self.animate_ellipsis) 
Example #3
Source File: output_option.py    From Pyslvs-UI with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(
        self,
        env: str,
        file_name: str,
        vpoints: Sequence[VPoint],
        v_to_slvs: Callable[[], Iterable[Tuple[int, int]]],
        parent: QWidget
    ):
        """Comes in environment variable and project name."""
        super(OutputDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setWindowTitle(f"Export {self.format_name} module project")
        self.setWindowIcon(QIcon(QPixmap(f":/icons/{self.format_icon}")))
        self.assembly_label.setText(self.assembly_description)
        self.frame_label.setText(self.frame_description)
        self.path_edit.setPlaceholderText(env)
        self.filename_edit.setPlaceholderText(file_name)
        self.vpoints = vpoints
        self.v_to_slvs = v_to_slvs 
Example #4
Source File: main_base.py    From Pyslvs-UI with GNU Affero General Public License v3.0 6 votes vote down vote up
def __undo_redo(self) -> None:
        """Undo list settings.

        + Undo stack.
        + Undo view widget.
        + Hot keys.
        """
        self.command_stack = QUndoStack(self)
        self.command_stack.setUndoLimit(self.prefer.undo_limit_option)
        self.command_stack.indexChanged.connect(self.command_reload)
        action_redo = self.command_stack.createRedoAction(self, "Redo")
        action_undo = self.command_stack.createUndoAction(self, "Undo")
        action_redo.setShortcuts(["Ctrl+Shift+Z", "Ctrl+Y"])
        action_redo.setStatusTip("Backtracking undo action.")
        action_redo.setIcon(QIcon(QPixmap(":/icons/redo.png")))
        action_undo.setShortcut("Ctrl+Z")
        action_undo.setStatusTip("Recover last action.")
        action_undo.setIcon(QIcon(QPixmap(":/icons/undo.png")))
        self.menu_edit.addActions([action_undo, action_redo]) 
Example #5
Source File: __init__.py    From Pyslvs-UI with GNU Affero General Public License v3.0 6 votes vote down vote up
def __add_result(self, result: Mapping[str, Any]) -> None:
        """Add result items, except add to the list."""
        item = QListWidgetItem(result['algorithm'])
        interrupt = result['interrupted']
        if interrupt == 'False':
            interrupt_icon = "task_completed.png"
        elif interrupt == 'N/A':
            interrupt_icon = "question.png"
        else:
            interrupt_icon = "interrupted.png"
        item.setIcon(QIcon(QPixmap(f":/icons/{interrupt_icon}")))
        if interrupt == 'False':
            interrupt_text = "No interrupt."
        else:
            interrupt_text = f"Interrupt at: {interrupt}"
        text = f"{result['algorithm']} ({interrupt_text})"
        if interrupt == 'N/A':
            text += "\n※Completeness is unknown."
        item.setToolTip(text)
        self.result_list.addItem(item) 
Example #6
Source File: edit_point.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(
        self,
        vpoints: List[VPoint],
        vlinks: List[VLink],
        pos: Union[int, bool],
        parent: QWidget
    ):
        """Input data reference from main window.

        + Needs VPoints and VLinks information.
        + If row is false: Create action.
        """
        super(EditPointDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        icon = self.windowIcon()
        self.icon = QIcon(QPixmap(":/icons/link.png"))
        self.vpoints = vpoints
        self.vlinks = vlinks
        vpoints_count = len(vpoints)
        for i, e in enumerate(color_names):
            self.color_box.insertItem(i, color_icon(e), e)
        for vlink in vlinks:
            self.no_selected.addItem(QListWidgetItem(self.icon, vlink.name))
        if pos is False:
            self.name_box.addItem(icon, f'Point{vpoints_count}')
            self.name_box.setEnabled(False)
            self.color_box.setCurrentIndex(self.color_box.findText('green'))
        else:
            for i in range(vpoints_count):
                self.name_box.insertItem(i, icon, f'Point{i}')
            self.name_box.setCurrentIndex(pos)
        self.type_box.currentIndexChanged.connect(self.__check_angle)
        self.__check_angle() 
Example #7
Source File: search.py    From conda-manager with MIT License 5 votes vote down vote up
def __init__(self, parent=None, icon=True):
        super(SearchLineEdit, self).__init__(parent)
        self.setTextMargins(1, 0, 20, 0)

        if icon:
            self.setTextMargins(18, 0, 20, 0)
            self._label = QLabel(self)
            self._pixmap_icon = QPixmap(get_image_path('conda_search.png'))
            self._label.setPixmap(self._pixmap_icon)
            self._label.setStyleSheet('''border: 0px; padding-bottom: 0px;
                                      padding-left: 2px;''')

        self._pixmap = QPixmap(get_image_path('conda_del.png'))
        self.button_clear = QToolButton(self)
        self.button_clear.setIcon(QIcon(self._pixmap))
        self.button_clear.setIconSize(QSize(18, 18))
        self.button_clear.setCursor(Qt.ArrowCursor)
        self.button_clear.setStyleSheet("""QToolButton
            {background: transparent;
            padding-right: 2px; border: none; margin:0px; }""")
        self.button_clear.setVisible(False)

        # Layout
        self._layout = QHBoxLayout(self)
        self._layout.addWidget(self.button_clear, 0, Qt.AlignRight)
        self._layout.setSpacing(0)
        self._layout.setContentsMargins(0, 2, 2, 0)

        # Signals and slots
        self.button_clear.clicked.connect(self.clear_text)
        self.textChanged.connect(self._toggle_visibility)
        self.textEdited.connect(self._toggle_visibility) 
Example #8
Source File: close.py    From conda-manager with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ClosePackageManagerDialog, self).__init__(*args, **kwargs)
        self.label_icon = QLabel()
        self.label_about = QLabel('Conda is still busy.\n\n'
                                  'Do you want to cancel the process?')
        self.button_ok = QPushButton('Yes')
        self.button_cancel = QPushButton('No')
        self.buttonbox = QDialogButtonBox(Qt.Horizontal)

        # Widget setup
        self.buttonbox.addButton(self.button_ok, QDialogButtonBox.ActionRole)
        self.buttonbox.addButton(self.button_cancel,
                                 QDialogButtonBox.ActionRole)
#        self.label_icon.setPixmap(QPixmap(images.ANACONDA_ICON_64_PATH))
        self.setWindowTitle("Cancel Process")

        # Layouts
        h_layout = QHBoxLayout()
        h_layout.addWidget(self.label_icon, 0, Qt.AlignTop)
        h_layout.addSpacing(10)
        h_layout.addWidget(self.label_about)

        main_layout = QVBoxLayout()
        main_layout.addLayout(h_layout)
        main_layout.addSpacing(20)
        main_layout.addWidget(self.buttonbox)
        self.setLayout(main_layout)

        # Signals
        self.button_ok.clicked.connect(self.accept)
        self.button_cancel.clicked.connect(self.reject) 
Example #9
Source File: schematics.py    From pyrpl with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, widget_name, y, filename, label, parent, x_offset=0):
        super(MyImage, self).__init__(widget_name, y, label, parent, x_offset)
        self.pixmap = QtGui.QPixmap(osp.join(IMAGE_PATH, filename))
        self.item.setPixmap(self.pixmap)
        self.item.setFixedSize(self.pixmap.size())

        self.label = QtWidgets.QLabel(label)
        self.lay.addWidget(self.label)


        #self.setText(self.widget_name) 
Example #10
Source File: script_ui.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.setEnabled(True)
        Dialog.resize(533, 564)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/icons/script.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Dialog.setWindowIcon(icon)
        Dialog.setAutoFillBackground(True)
        Dialog.setSizeGripEnabled(True)
        Dialog.setModal(True)
        self.main_layout = QtWidgets.QVBoxLayout(Dialog)
        self.main_layout.setObjectName("main_layout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.show_qrcode = QtWidgets.QPushButton(Dialog)
        self.show_qrcode.setAutoDefault(False)
        self.show_qrcode.setObjectName("show_qrcode")
        self.horizontalLayout.addWidget(self.show_qrcode)
        self.copy_button = QtWidgets.QPushButton(Dialog)
        self.copy_button.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
        self.copy_button.setAutoDefault(False)
        self.copy_button.setObjectName("copy_button")
        self.horizontalLayout.addWidget(self.copy_button)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.button_box = QtWidgets.QDialogButtonBox(Dialog)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.button_box.sizePolicy().hasHeightForWidth())
        self.button_box.setSizePolicy(sizePolicy)
        self.button_box.setOrientation(QtCore.Qt.Horizontal)
        self.button_box.setStandardButtons(QtWidgets.QDialogButtonBox.Close|QtWidgets.QDialogButtonBox.Save)
        self.button_box.setObjectName("button_box")
        self.horizontalLayout.addWidget(self.button_box)
        self.main_layout.addLayout(self.horizontalLayout)

        self.retranslateUi(Dialog)
        self.button_box.rejected.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog) 
Example #11
Source File: main_base.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __free_move(self) -> None:
        """Menu of free move mode."""

        def free_move_mode_func(j: int, icon_qt: QIcon) -> Callable[[], None]:
            @Slot()
            def func() -> None:
                self.free_move_button.setIcon(icon_qt)
                self.main_canvas.set_free_move(j)
                self.entities_tab.setCurrentIndex(0)
                self.inputs_widget.variable_stop.click()

            return func

        menu = QMenu(self)
        for i, (text, icon, tip) in enumerate([
            ("View mode", "free_move_off", "Disable free move mode."),
            ("Translate mode", "translate", "Edit by 2 DOF moving."),
            ("Rotate mode", "rotate", "Edit by 1 DOF moving."),
            ("Reflect mode", "reflect", "Edit by flip axis."),
        ]):
            action = QAction(QIcon(QPixmap(f":/icons/{icon}.png")), text, self)
            action.triggered.connect(free_move_mode_func(i, action.icon()))
            action.setShortcut(f"Ctrl+{i + 1}")
            action.setShortcutContext(Qt.WindowShortcut)
            action.setStatusTip(tip)
            menu.addAction(action)
            if i == 0:
                self.free_move_disable = action
        self.free_move_button.setMenu(menu) 
Example #12
Source File: undo_redo.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def undo(self) -> None:
        """Create a new item and recover expression."""
        item = QListWidgetItem(self.name)
        item.expr = self.mechanism
        item.setIcon(QIcon(QPixmap(":/icons/mechanism.png")))
        self.widget.insertItem(self.row, item) 
Example #13
Source File: undo_redo.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def redo(self) -> None:
        """Add mechanism expression to 'expr' attribute."""
        item = QListWidgetItem(self.name)
        item.expr = self.mechanism
        item.setIcon(QIcon(QPixmap(":/icons/mechanism.png")))
        self.widget.addItem(item) 
Example #14
Source File: QComplexWidgets.py    From pylustrator with GNU General Public License v3.0 5 votes vote down vote up
def icon(self, name: str):
        """ get an icon with the given filename """
        pm = QtGui.QPixmap(os.path.join(os.path.dirname(__file__), "icons", name))
        if hasattr(pm, 'setDevicePixelRatio'):
            pm.setDevicePixelRatio(self.canvas._dpi_ratio)
        return QtGui.QIcon(pm) 
Example #15
Source File: edit_link.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(
        self,
        vpoints: List[VPoint],
        vlinks: List[VLink],
        row: Union[int, bool],
        parent: QWidget
    ):
        """Input data reference from main window.

        + Needs VPoints and VLinks information.
        + If row is false: Create action.
        """
        super(EditLinkDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.vpoints = vpoints
        self.vlinks = vlinks
        icon = self.windowIcon()
        self.icon = QIcon(QPixmap(":/icons/bearing.png"))
        for i, e in enumerate(color_names):
            self.color_box.insertItem(i, color_icon(e), e)
        for i in range(len(self.vpoints)):
            self.no_selected.addItem(QListWidgetItem(self.icon, f'Point{i}'))
        if row is False:
            names = {vlink.name for vlink in self.vlinks}
            n = 1
            name = f"link_{n}"
            while name in names:
                n += 1
                name = f"link_{n}"
            self.name_edit.setText(name)
            self.name_box.setEnabled(False)
            self.name_box.addItem(icon, "New link")
            self.color_box.setCurrentIndex(self.color_box.findText('blue'))
        else:
            for i, vlink in enumerate(self.vlinks):
                self.name_box.insertItem(i, icon, vlink.name)
            self.name_box.setCurrentIndex(row)
        self.name_edit.textChanged.connect(self.__is_ok)
        self.__is_ok() 
Example #16
Source File: structure_widget.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __save_atlas(self) -> None:
        """Save function as same as type synthesis widget."""
        count = self.collection_list.count()
        if count < 1:
            return
        lateral, ok = QInputDialog.getInt(
            self,
            "Atlas",
            "The number of lateral:",
            5, 1
        )
        if not ok:
            return
        file_name = self.output_to("atlas image", qt_image_format)
        if not file_name:
            return
        icon_size = self.collection_list.iconSize()
        width = icon_size.width()
        image = self.collection_list.item(0).icon().pixmap(icon_size).toImage()
        image_main = QImage(QSize(
            lateral if count > lateral else count,
            (count // lateral) + bool(count % lateral)
        ) * width, image.format())
        image_main.fill(Qt.transparent)
        painter = QPainter(image_main)
        for row in range(count):
            image = self.collection_list.item(row).icon().pixmap(icon_size).toImage()
            painter.drawImage(QPointF(row % lateral, row // lateral) * width, image)
        painter.end()
        pixmap = QPixmap()
        pixmap.convertFromImage(image_main)
        pixmap.save(file_name)
        self.save_reply_box("Atlas", file_name) 
Example #17
Source File: structure_widget.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __save_graph(self) -> None:
        """Save the current graph."""
        if self.selection_window.count() != 1:
            return
        file_name = self.output_to("atlas image", qt_image_format)
        if not file_name:
            return
        pixmap: QPixmap = self.selection_window.item(0).icon().pixmap(self.selection_window.iconSize())
        pixmap.save(file_name)
        self.save_reply_box("Graph", file_name) 
Example #18
Source File: __init__.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: MainWindowBase):
        """Create two widget page and using main window to make their parent."""
        super(Collections, self).__init__(parent)
        layout = QVBoxLayout(self)
        self.tab_widget = QTabWidget(self)
        layout.addWidget(self.tab_widget)
        self.setWindowIcon(QIcon(QPixmap(":/icons/collections.png")))
        self.structure_widget = StructureWidget(parent)
        self.configure_widget = ConfigureWidget(
            self.structure_widget.add_collection,
            parent
        )
        self.tab_widget.addTab(
            self.structure_widget,
            self.structure_widget.windowIcon(),
            "Structures"
        )
        self.tab_widget.addTab(
            self.configure_widget,
            self.configure_widget.windowIcon(),
            "Configuration"
        )
        self.structure_widget.configure_button.clicked.connect(
            lambda: self.tab_widget.setCurrentIndex(1)
        )
        self.structure_widget.layout_sender.connect(
            self.configure_widget.set_graph
        ) 
Example #19
Source File: wfile.py    From pyCGNS with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self):
        super(Q7FileIconProvider, self).__init__()
        self.dir = QIcon(QPixmap(":/images/icons/folder.png"))
        self.cgns = QIcon(QPixmap(":/images/icons/tree-load.png"))
        self.empty = QIcon() 
Example #20
Source File: FileRevisionWindow.py    From P4VFX with MIT License 5 votes vote down vote up
def setRevisionTableColumn(self, row, column, value, icon=None, isLongText=False):
        value = str(value)

        widget = QtWidgets.QWidget()
        layout = QtWidgets.QHBoxLayout()
        layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignHCenter)

        # Use a QLineEdit to allow the text to be copied if the data is large
        if isLongText:
            textLabel = QtWidgets.QLineEdit()
            textLabel.setText(value)
            textLabel.setCursorPosition(0)
            textLabel.setReadOnly(True)
            textLabel.setStyleSheet("QLineEdit { border: none }")
        else:
            textLabel = QtWidgets.QLabel(value)
            textLabel.setStyleSheet("QLabel { border: none } ")

        # layout.setContentsMargins(4, 0, 4, 0)
        
        if icon:
            iconPic = QtGui.QPixmap(icon)
            iconPic = iconPic.scaled(16, 16)
            iconLabel = QtWidgets.QLabel()
            iconLabel.setPixmap(iconPic)
            layout.addWidget(iconLabel)
        layout.addWidget(textLabel)

        widget.setLayout(layout)

        self.tableWidget.setCellWidget(row, column, widget) 
Example #21
Source File: FileRevisionWindow.py    From P4VFX with MIT License 5 votes vote down vote up
def setRevisionTableColumn(self, row, column, value, icon=None, isLongText=False):
        value = str(value)

        widget = QtWidgets.QWidget()
        layout = QtWidgets.QHBoxLayout()
        layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignHCenter)

        # Use a QLineEdit to allow the text to be copied if the data is large
        if isLongText:
            textLabel = QtWidgets.QLineEdit()
            textLabel.setText(value)
            textLabel.setCursorPosition(0)
            textLabel.setReadOnly(True)
            textLabel.setStyleSheet("QLineEdit { border: none }")
        else:
            textLabel = QtWidgets.QLabel(value)
            textLabel.setStyleSheet("QLabel { border: none } ")

        # layout.setContentsMargins(4, 0, 4, 0)
        
        if icon:
            iconPic = QtGui.QPixmap(icon)
            iconPic = iconPic.scaled(16, 16)
            iconLabel = QtWidgets.QLabel()
            iconLabel.setPixmap(iconPic)
            layout.addWidget(iconLabel)
        layout.addWidget(textLabel)

        widget.setLayout(layout)

        self.tableWidget.setCellWidget(row, column, widget) 
Example #22
Source File: utils.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def drag_with_pixmap(list_widget: QListWidget) -> QDrag:
    """Create a QDrag object with a pixmap of the currently select list item.

    This method is useful when you have a QListWidget that displays custom
    widgets for each QListWidgetItem instance in the list (usually by calling
    ``QListWidget.setItemWidget(item, widget)``).  When used in a
    ``QListWidget.startDrag`` method, this function creates a QDrag object that
    shows an image of the item being dragged (rather than an empty rectangle).

    Parameters
    ----------
    list_widget : QListWidget
        The QListWidget for which to create a QDrag object.

    Returns
    -------
    QDrag
        A QDrag instance with a pixmap of the currently selected item.

    Example
    -------
    >>> class QListWidget:
    ...     def startDrag(self, supportedActions):
    ...         drag = drag_with_pixmap(self)
    ...         drag.exec_(supportedActions, Qt.MoveAction)

    """
    drag = QDrag(list_widget)
    drag.setMimeData(list_widget.mimeData(list_widget.selectedItems()))
    size = list_widget.viewport().visibleRegion().boundingRect().size()
    pixmap = QPixmap(size)
    pixmap.fill(Qt.transparent)
    painter = QPainter(pixmap)
    for index in list_widget.selectedIndexes():
        rect = list_widget.visualRect(index)
        painter.drawPixmap(rect, list_widget.viewport().grab(rect))
    painter.end()
    drag.setPixmap(pixmap)
    drag.setHotSpot(list_widget.viewport().mapFromGlobal(QCursor.pos()))
    return drag 
Example #23
Source File: utils.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def square_pixmap(size):
    """Create a white/black hollow square pixmap. For use as labels cursor."""
    pixmap = QPixmap(QSize(size, size))
    pixmap.fill(Qt.transparent)
    painter = QPainter(pixmap)
    painter.setPen(Qt.white)
    painter.drawRect(0, 0, size - 1, size - 1)
    painter.setPen(Qt.black)
    painter.drawRect(1, 1, size - 3, size - 3)
    painter.end()
    return pixmap 
Example #24
Source File: __main__.py    From Pyslvs-UI with GNU Affero General Public License v3.0 4 votes vote down vote up
def main() -> None:
    """Startup function."""
    global _app
    t0 = process_time()
    exit_code = 0
    from sys import argv, exit
    from logging import shutdown
    from platform import system
    from .info import ARGUMENTS, logger
    if ARGUMENTS.cmd in {'gui', None}:
        from qtpy.QtCore import Qt, qInstallMessageHandler
        from qtpy.QtWidgets import QApplication, QSplashScreen
        from qtpy.QtGui import QPixmap
        _app = QApplication(argv)
        # Depress Qt warning
        qInstallMessageHandler(lambda _0, _1, _2: None)
        # Load QRC file
        from pyslvs_ui.icons_rc import qInitResources
        qInitResources()
        # Splash
        sp = QSplashScreen(QPixmap(":/icons/splash.png"))
        sp.showMessage(f"{__author__} {__copyright__}",
                       Qt.AlignBottom | Qt.AlignRight)
        sp.show()
        # Force enable fusion style on macOS
        if system() == 'Darwin':
            ARGUMENTS.fusion = True
        if ARGUMENTS.fusion:
            _app.setStyle('fusion')
        # Main window
        from .main_window import MainWindow
        w = MainWindow.new()
        sp.finish(w)
        sp.deleteLater()
        logger.info(f"Startup with: {process_time() - t0:.02f}s")
        if not ARGUMENTS.debug_mode:
            w.console_connect()
        del sp, w
        exit_code = _app.exec_()
    elif ARGUMENTS.cmd == 'test':
        from importlib import import_module
        import_module('pyslvs_ui.main_window')
        logger.info("All module loaded successfully.")
        logger.info(f"Loaded with: {process_time() - t0:.02f}s")
    elif ARGUMENTS.cmd == 'extract':
        logger.info(f"Start CLI: {process_time() - t0:.02f}s")
        # TODO: CLI mode
    else:
        raise ValueError(f"unknown command: {ARGUMENTS.cmd}")
    shutdown()
    exit(exit_code) 
Example #25
Source File: preview.py    From Pyslvs-UI with GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(
        self,
        vpoints: Sequence[VPoint],
        vlinks: Sequence[VLink],
        path: _Paths,
        slider_path: _SliderPaths,
        monochrome: bool,
        parent: QWidget
    ):
        super(AnimateDialog, self).__init__(parent)
        self.setWindowTitle("Vector Animation")
        self.setWindowFlags(self.windowFlags() | Qt.WindowMaximizeButtonHint
                            & ~Qt.WindowContextHelpButtonHint)
        self.setMinimumSize(800, 600)
        self.setModal(True)
        main_layout = QVBoxLayout(self)
        layout = QHBoxLayout(self)
        self.label = QLabel(self)
        layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum))
        layout.addWidget(self.label)
        main_layout.addLayout(layout)
        self.canvas = _DynamicCanvas(vpoints, vlinks, path, slider_path, self)
        self.canvas.set_monochrome_mode(monochrome)
        self.canvas.update_pos.connect(self.__set_pos)
        main_layout.addWidget(self.canvas)
        layout = QHBoxLayout(self)
        self.play = QPushButton(QIcon(QPixmap(":/icons/play.png")), "", self)
        self.play.setCheckable(True)
        self.play.clicked.connect(self.__play)
        layout.addWidget(self.play)
        self.slider = QSlider(Qt.Horizontal, self)
        self.slider.setMaximum(max(len(p) for p in path) - 1)
        self.slider.valueChanged.connect(self.canvas.set_index)
        layout.addWidget(self.slider)
        factor = QDoubleSpinBox(self)
        factor.valueChanged.connect(self.canvas.set_factor)
        factor.setRange(0.01, 9999)
        factor.setValue(50)
        layout.addWidget(factor)
        main_layout.addLayout(layout)
        self.timer = QTimer()
        self.timer.setInterval(10)
        self.timer.timeout.connect(self.__move_ind) 
Example #26
Source File: script.py    From pyCGNS with GNU Lesser General Public License v2.1 4 votes vote down vote up
def run(args=[], files=[], datasets=[],
        flags=(False, False, False, False, False, False, False),
        ppath=None, query=None):
    hidecontrol = False
    global splash
    global wcontrol
    
    if flags[4]:
        from CGNS.NAV.wquery import Q7Query
        Q7Query.loadUserQueries()
        Q7Query.fillQueries()
        ql = Q7Query.queriesNamesList()
        print('# CGNS.NAV available queries:')
        for q in ql:
            print(' ', q)
    else:
        app = QApplication(args)
        if not flags[5]:
            pixmap = QPixmap(":/images/splash.png")
            splash = QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
            splash.show()
            splash.showMessage("Release v%s" % OCTXT._ToolVersion,
                               QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom)
            timer = QtCore.QTimer.singleShot(3000,closeSplash)
        app.processEvents()
        Q7Main.verbose = flags[2]
        wcontrol = Q7Main()
        wcontrol._application = app
        wcontrol.setOptionValue('NAVTrace', flags[2])
        wcontrol.transientRecurse = flags[0]
        wcontrol.transientVTK = flags[3]
        wcontrol.query = query
        wcontrol._T('start')
        wcontrol.setDefaults()
        if flags[1]:
            wcontrol.loadlast()
            hidecontrol = flags[6]
        if files:
            for ff in files:
                wcontrol.loadfile(ff)
            hidecontrol = flags[6]
        if datasets:
            for dd in datasets:
                wcontrol.loadCompleted(dataset_name='FFFF',
                                       dataset_base='BASE',
                                       dataset_tree=dd,
                                       dataset_references=[],
                                       dataset_paths=[])
            hidecontrol = flags[6]
        wcontrol.show()
        if hidecontrol:
            wcontrol.hide()
        app.exec_()
        wcontrol._T('leave')
    sys.exit()


# run()

# ----------------------------------------------------------------- 
Example #27
Source File: overview.py    From Pyslvs-UI with GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(
        self,
        parent: QWidget,
        title: str,
        main_expr: str,
        storage_data: Mapping[str, str],
        input_data: Sequence[Tuple[int, int]],
        path_data: Mapping[str, _Paths],
        collection_data: Sequence[_Pairs],
        config_data: Mapping[str, Mapping[str, Any]],
        algorithm_data: Sequence[Mapping[str, Any]],
        background_path: str
    ):
        """Data come from commit."""
        super(OverviewDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setWindowTitle(f"Project: {title}")

        # Expression of storage data
        self.main_expr.setText(main_expr)
        for name, expr in storage_data.items():
            item = QListWidgetItem(f"[{name}]: {expr}")
            item.setToolTip(expr)
            self.storage_list.addItem(item)
        size = len(storage_data)
        if main_expr != "M[]":
            size += 1
        self.__set_item_text(0, size)
        # Expression of inputs variable data and Path data
        for a, b in input_data:
            self.variables_list.addItem(f"Point{a}->Point{b}")
        for name, paths in path_data.items():
            item = QListWidgetItem(name)
            item.setToolTip(", ".join(
                f'[{i}]' for i, path in enumerate(paths) if path
            ))
            self.records_list.addItem(item)
        self.__set_item_text(1, len(input_data), len(path_data))
        # Structure collections and Triangle collections
        for edges in collection_data:
            self.structures_list.addItem(str(edges))
        for name, data in config_data.items():
            item = QListWidgetItem(name)
            item.setToolTip(data['expression'])
            self.triangular_iteration_list.addItem(item)
        self.__set_item_text(2, len(collection_data), len(config_data))
        # Dimensional synthesis
        for data in algorithm_data:
            self.results_list.addItem(data['algorithm'])
        self.__set_item_text(3, len(algorithm_data))
        # Background image
        self.image_path.setText(background_path)
        self.__set_item_text(4, 1 if background_path else 0)
        self.background_preview.setPixmap(QPixmap(background_path)) 
Example #28
Source File: mainwindow.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def closeEvent(self, event):
        """ Forward the close event to every tabs contained by the windows
        """
        if self.tab_widget.count() == 0:
            # no tabs, just close
            event.accept()
            return
        # Do Not loop on the widget count as it change while closing
        title = self.window().windowTitle()
        cancel = QtWidgets.QMessageBox.Cancel
        okay = QtWidgets.QMessageBox.Ok
        accept_role = QtWidgets.QMessageBox.AcceptRole

        if self.confirm_exit:
            if self.tab_widget.count() > 1:
                msg = "Close all tabs, stop all kernels, and Quit?"
            else:
                msg = "Close console, stop kernel, and Quit?"
            info = "Kernels not started here (e.g. notebooks) will be left alone."
            closeall = QtWidgets.QPushButton("&Quit", self)
            closeall.setShortcut('Q')
            box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question,
                                    title, msg)
            box.setInformativeText(info)
            box.addButton(cancel)
            box.addButton(closeall, QtWidgets.QMessageBox.YesRole)
            box.setDefaultButton(closeall)
            box.setEscapeButton(cancel)
            pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(64,64)))
            box.setIconPixmap(pixmap)
            reply = box.exec_()
        else:
            reply = okay

        if reply == cancel:
            event.ignore()
            return
        if reply == okay or reply == accept_role:
            while self.tab_widget.count() >= 1:
                # prevent further confirmations:
                widget = self.active_frontend
                widget._confirm_exit = False
                self.close_tab(widget)
            event.accept() 
Example #29
Source File: event_loop.py    From napari with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def gui_qt(*, startup_logo=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool
        Show a splash screen with the napari logo during startup.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    splash_widget = None
    app = QApplication.instance()
    if not app:
        # automatically determine monitor DPI.
        # Note: this MUST be set before the QApplication is instantiated
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        # if this is the first time the Qt app is being instantiated, we set
        # the name, so that we know whether to raise_ in Window.show()
        app = _create_application(sys.argv)
        app.setApplicationName('napari')
        if startup_logo:
            logopath = join(dirname(__file__), '..', 'resources', 'logo.png')
            pm = QPixmap(logopath).scaled(
                360, 360, Qt.KeepAspectRatio, Qt.SmoothTransformation
            )
            splash_widget = QSplashScreen(pm)
            splash_widget.show()
            app._splash_widget = splash_widget
    else:
        app._existed = True
    yield app
    # if the application already existed before this function was called,
    # there's no need to start it again.  By avoiding unnecessary calls to
    # ``app.exec_``, we avoid blocking.
    if app.applicationName() == 'napari':
        if splash_widget and startup_logo:
            splash_widget.close()
        app.exec_()