コード例 #1
0
 def handleTileDataLoaded(self, x, y, zoom, data):
     pix = QPixmap()
     pix.loadFromData(data)
     self.tileReceived.emit(x, y, zoom, pix)
コード例 #2
0
ファイル: qt_viewer.py プロジェクト: wconnell/napari
    def __init__(self, viewer):
        super().__init__()

        QCoreApplication.setAttribute(
            Qt.AA_UseStyleSheetPropagationInWidgetStyles, True)

        self.viewer = viewer
        self.dims = QtDims(self.viewer.dims)
        self.controls = QtControls(self.viewer)
        self.layers = QtLayerList(self.viewer.layers)
        self.layerButtons = QtLayerButtons(self.viewer)
        self.viewerButtons = QtViewerButtons(self.viewer)
        self.console = QtConsole({'viewer': self.viewer})

        # This dictionary holds the corresponding vispy visual for each layer
        self.layer_to_visual = {}

        if self.console.shell is not None:
            self.console.style().unpolish(self.console)
            self.console.style().polish(self.console)
            self.console.hide()
            self.viewerButtons.consoleButton.clicked.connect(
                lambda: self._toggle_console())
        else:
            self.viewerButtons.consoleButton.setEnabled(False)

        self.canvas = SceneCanvas(keys=None, vsync=True)
        self.canvas.events.ignore_callback_errors = False
        self.canvas.native.setMinimumSize(QSize(200, 200))
        self.canvas.context.set_depth_func('lequal')

        self.canvas.connect(self.on_mouse_move)
        self.canvas.connect(self.on_mouse_press)
        self.canvas.connect(self.on_mouse_release)
        self.canvas.connect(self.on_key_press)
        self.canvas.connect(self.on_key_release)
        self.canvas.connect(self.on_draw)

        self.view = self.canvas.central_widget.add_view()
        self._update_camera()

        main_widget = QWidget()
        main_layout = QGridLayout()
        main_layout.setContentsMargins(15, 20, 15, 10)
        main_layout.addWidget(self.canvas.native, 0, 1, 3, 1)
        main_layout.addWidget(self.dims, 3, 1)
        main_layout.addWidget(self.controls, 0, 0)
        main_layout.addWidget(self.layerButtons, 1, 0)
        main_layout.addWidget(self.layers, 2, 0)
        main_layout.addWidget(self.viewerButtons, 3, 0)
        main_layout.setColumnStretch(1, 1)
        main_layout.setSpacing(10)
        main_widget.setLayout(main_layout)

        self.setOrientation(Qt.Vertical)
        self.addWidget(main_widget)
        if self.console.shell is not None:
            self.addWidget(self.console)

        self._last_visited_dir = str(Path.home())

        self._cursors = {
            'disabled':
            QCursor(
                QPixmap(':/icons/cursor/cursor_disabled.png').scaled(20, 20)),
            'cross':
            Qt.CrossCursor,
            'forbidden':
            Qt.ForbiddenCursor,
            'pointing':
            Qt.PointingHandCursor,
            'standard':
            QCursor(),
        }

        self._update_palette(viewer.palette)

        self._key_release_generators = {}

        self.viewer.events.interactive.connect(self._on_interactive)
        self.viewer.events.cursor.connect(self._on_cursor)
        self.viewer.events.reset_view.connect(self._on_reset_view)
        self.viewer.events.palette.connect(
            lambda event: self._update_palette(event.palette))
        self.viewer.layers.events.reordered.connect(self._reorder_layers)
        self.viewer.layers.events.added.connect(self._add_layer)
        self.viewer.layers.events.removed.connect(self._remove_layer)
        self.viewer.dims.events.camera.connect(
            lambda event: self._update_camera())

        self.setAcceptDrops(True)
コード例 #3
0
ファイル: install.py プロジェクト: zhoufan766/spyder
    def __init__(self, parent):
        super(KiteInstallation, self).__init__(parent)

        # Left side
        action_layout = QVBoxLayout()
        progress_layout = QHBoxLayout()
        self._progress_widget = QWidget(self)
        self._progress_widget.setFixedHeight(50)
        self._progress_filter = HoverEventFilter()
        self._progress_bar = QProgressBar(self)
        self._progress_bar.setFixedWidth(180)
        self._progress_widget.installEventFilter(self._progress_filter)
        self.cancel_button = QPushButton()
        self.cancel_button.setIcon(ima.icon('DialogCloseButton'))
        self.cancel_button.hide()
        progress_layout.addWidget(self._progress_bar, alignment=Qt.AlignLeft)
        progress_layout.addWidget(self.cancel_button)
        self._progress_widget.setLayout(progress_layout)

        self._progress_label = QLabel(_('Downloading'))
        install_info = QLabel(
            _("Kite comes with a native app called the Copilot <br>"
              "which provides you with real time <br>"
              "documentation as you code.<br><br>"
              "When Kite is done installing, the Copilot will <br>"
              "launch automatically and guide you throught the <br>"
              "rest of the setup process."))

        button_layout = QHBoxLayout()
        self.ok_button = QPushButton(_('OK'))
        button_layout.addStretch()
        button_layout.addWidget(self.ok_button)
        button_layout.addStretch()

        action_layout.addStretch()
        action_layout.addWidget(self._progress_label)
        action_layout.addWidget(self._progress_widget)
        action_layout.addWidget(install_info)
        action_layout.addSpacing(10)
        action_layout.addLayout(button_layout)
        action_layout.addStretch()

        # Right side
        copilot_image_source = get_image_path('kite_copilot.png')

        copilot_image = QPixmap(copilot_image_source)
        copilot_label = QLabel()
        screen = QApplication.primaryScreen()
        device_pixel_ratio = screen.devicePixelRatio()
        if device_pixel_ratio > 1:
            copilot_image.setDevicePixelRatio(device_pixel_ratio)
            copilot_label.setPixmap(copilot_image)
        else:
            image_height = copilot_image.height() * 0.4
            image_width = copilot_image.width() * 0.4
            copilot_label.setPixmap(
                copilot_image.scaled(image_width, image_height,
                                     Qt.KeepAspectRatio,
                                     Qt.SmoothTransformation))

        # Layout
        general_layout = QHBoxLayout()
        general_layout.addLayout(action_layout)
        general_layout.addWidget(copilot_label)

        self.setLayout(general_layout)

        # Signals
        self._progress_filter.sig_hover_enter.connect(
            lambda: self.cancel_button.show())
        self._progress_filter.sig_hover_leave.connect(
            lambda: self.cancel_button.hide())
コード例 #4
0
    def __init__(self, parent):
        """Create About Spyder dialog with general information."""
        QDialog.__init__(self, parent)
        self.setWindowFlags(
            self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        versions = get_versions()
        # Show Git revision for development version
        revlink = ''
        if versions['revision']:
            rev = versions['revision']
            revlink = " (<a href='https://github.com/spyder-ide/spyder/" \
                      "commit/%s'>Commit: <br> %s</a>)" % (rev, rev)

        # Get current font properties
        font = self.font()
        font_family = font.family()
        buttons_padding = DialogStyle.ButtonsPadding
        buttons_font_size = DialogStyle.ButtonsFontSize
        font_size = DialogStyle.ContentFontSize
        dialog_background_color = QStylePalette.COLOR_BACKGROUND_2
        self.label_overview = QLabel((
            """
            <div style='font-family: "{font_family}";
                        font-size: {font_size};
                        font-weight: normal;
                        '>
            <br>
            <p>
            <b> Spyder IDE</b>
            <br> <br>
            The Scientific Python Development Environment |
            <a href="{website_url}">Spyder-IDE.org</a>
            <br>
            <p>
            Python {python_ver} {bitness}-bit | Qt {qt_ver} |
            {qt_api} {qt_api_ver} | {os_name} {os_ver}
            </p>
            <br> <br>
            <a href="{github_url}">GitHub </a>| <a href="{twitter_url}">
            Twitter </a>|
            <a href="{facebook_url}">Facebook </a>| <a href="{youtube_url}">
            YouTube </a>|
            <a href="{instagram_url}">Instagram </a>

            </div>""").format(
                website_url=__website_url__,
                github_url=__project_url__,
                twitter_url="https://twitter.com/Spyder_IDE",
                facebook_url="https://www.facebook.com/SpyderIDE",
                youtube_url="https://www.youtube.com/Spyder-IDE",
                instagram_url="https://www.instagram.com/spyderide/",
                python_ver=versions['python'],
                bitness=versions['bitness'],
                qt_ver=versions['qt'],
                qt_api=versions['qt_api'],
                qt_api_ver=versions['qt_api_ver'],
                os_name=versions['system'],
                os_ver=versions['release'],
                font_family=font_family,
                font_size=font_size,
            )
        )

        self.label_community = QLabel((
            """
            <div style='font-family: "{font_family}";
                        font-size: {font_size};
                        font-weight: normal;
                        '>
            <br>
            <p>
            Created by Pierre Raybaut; current maintainer is Carlos Cordoba.
            Developed by the
            <a href="{github_url}/graphs/contributors">international
            Spyder community</a>. Many thanks to all the Spyder beta testers
            and dedicated users.
            </p>
            <p>For help with Spyder errors and crashes, please read our
            <a href="{trouble_url}">Troubleshooting Guide</a>, and for bug
            reports and feature requests, visit our
            <a href="{github_url}">Github site</a>. For project discussion,
            see our <a href="{forum_url}">Google Group</a>.
            </p>
            <p>
            This project is part of a larger effort to promote and
            facilitate the use of Python for scientific and engineering
            software development.
            The popular Python distributions
            <a href="https://www.anaconda.com/download/">Anaconda</a> and
            <a href="https://winpython.github.io/">WinPython</a>
            also contribute to this plan.
            </p>
            </div>""").format(
                github_url=__project_url__,
                trouble_url=__trouble_url__,
                forum_url=__forum_url__,
                font_family=font_family,
                font_size=font_size,
            ))
        self.label_legal = QLabel((
            """
            <div style='font-family: "{font_family}";
                        font-size: {font_size};
                        font-weight: normal;
                        '>
            <br>
            <p>
            Copyright &copy; 2009-2020 Spyder Project Contributors and
            <a href="{github_url}/blob/master/AUTHORS.txt">others</a>.
            Distributed under the terms of the
            <a href="{github_url}/blob/master/LICENSE.txt">MIT License</a>.
            </p>
            <p>
            <p>Certain source files under other compatible permissive
            licenses and/or originally by other authors.
            Spyder 3 theme icons derived from
            <a href="https://fontawesome.com/">Font Awesome</a> 4.7
            (&copy; 2016 David Gandy; SIL OFL 1.1) and
            <a href="http://materialdesignicons.com/">Material Design</a>
            (&copy; 2014 Austin Andrews; SIL OFL 1.1).
            Most Spyder 2 theme icons sourced from the
            <a href="https://www.everaldo.com">Crystal Project iconset</a>
            (&copy; 2006-2007 Everaldo Coelho; LGPL 2.1+).
            Other icons from
            <a href="http://p.yusukekamiyamane.com/">Yusuke Kamiyamane</a>
            (&copy; 2013 Yusuke Kamiyamane; CC-BY 3.0),
            the <a href="http://www.famfamfam.com/lab/icons/silk/">FamFamFam
            Silk icon set</a> 1.3 (&copy; 2006 Mark James; CC-BY 2.5), and
            the <a href="https://www.kde.org/">KDE Oxygen icons</a>
            (&copy; 2007 KDE Artists; LGPL 3.0+).
            </p>
            <p>
            Splash screen photo by
            <a href="https://unsplash.com/@benchaccounting?utm_source=
            unsplash&utm_medium=referral&utm_content=creditCopyText">Bench
            Accounting</a> on <a href="https://unsplash.com/?utm_source=
            unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash
            </a>
            </p>
            <p>
            See the <a href="{github_url}/blob/master/NOTICE.txt">NOTICE</a>
            file for full legal information.
            </p>
            </div>
            """).format(
                github_url=__project_url__,
                font_family=font_family,
                font_size=font_size,
            )
        )

        for label in [self.label_overview, self.label_community,
                      self.label_legal]:
            label.setWordWrap(True)
            label.setAlignment(Qt.AlignTop)
            label.setOpenExternalLinks(True)
            label.setTextInteractionFlags(Qt.TextBrowserInteraction)
            label.setContentsMargins(15, 0, 25, 0)

        icon_filename = "spyder_about"
        pixmap = QPixmap(get_image_path(icon_filename))
        self.label_pic = QLabel(self)
        self.label_pic.setPixmap(
            pixmap.scaledToWidth(100, Qt.SmoothTransformation))
        self.label_pic.setAlignment(Qt.AlignBottom)
        self.info = QLabel((
            """
            <div style='font-family: "{font_family}";
                font-size: {font_size};
                font-weight: normal;
                '>
            <p>
            <b>Spyder IDE</b>
            <br>{spyder_ver}
            <br> {revision}
            <br> """).format(
            spyder_ver=versions['spyder'],
            revision=revlink,
            font_family=font_family,
            font_size=font_size))
        self.info.setAlignment(Qt.AlignHCenter)

        btn = QPushButton(_("Copy version info"), )
        bbox = QDialogButtonBox(QDialogButtonBox.Ok)
        bbox.setStyleSheet(
           f"font-size: {buttons_font_size};"
           f"padding: {buttons_padding}"
         )
        btn.setStyleSheet(
           f"font-size: {buttons_font_size};"
           f"padding: {buttons_padding}"
         )

        # Widget setup
        self.setWindowIcon(ima.icon('MessageBoxInformation'))
        self.setModal(False)

        # Layout
        piclayout = QVBoxLayout()
        piclayout.addWidget(self.label_pic)
        piclayout.addWidget(self.info)
        piclayout.setContentsMargins(20, 0, 15, 0)

        scroll_overview = QScrollArea(self)
        scroll_overview.setWidgetResizable(True)
        scroll_overview.setWidget(self.label_overview)

        scroll_community = QScrollArea(self)
        scroll_community.setWidgetResizable(True)
        scroll_community.setWidget(self.label_community)

        scroll_legal = QScrollArea(self)
        scroll_legal.setWidgetResizable(True)
        scroll_legal.setWidget(self.label_legal)

        self.tabs = QTabWidget()
        self.tabs.addTab(scroll_overview, _('Overview'))
        self.tabs.addTab(scroll_community, _('Community'))
        self.tabs.addTab(scroll_legal, _('Legal'))
        self.tabs.setStyleSheet(
            f"background-color: {dialog_background_color}")
        tabslayout = QHBoxLayout()
        tabslayout.addWidget(self.tabs)
        tabslayout.setSizeConstraint(tabslayout.SetFixedSize)
        tabslayout.setContentsMargins(0, 15, 15, 0)

        btmhlayout = QHBoxLayout()
        btmhlayout.addWidget(btn)
        btmhlayout.addWidget(bbox)
        btmhlayout.setContentsMargins(100, 20, 0, 20)
        btmhlayout.addStretch()

        vlayout = QVBoxLayout()
        vlayout.addLayout(tabslayout)
        vlayout.addLayout(btmhlayout)
        vlayout.setSizeConstraint(vlayout.SetFixedSize)

        mainlayout = QHBoxLayout(self)
        mainlayout.addLayout(piclayout)
        mainlayout.addLayout(vlayout)

        # Signals
        btn.clicked.connect(self.copy_to_clipboard)
        bbox.accepted.connect(self.accept)

        # Size
        self.resize(550, 430)

        # Style
        css = APP_STYLESHEET.get_copy()
        css = css.get_stylesheet()
        css.QDialog.setValues(backgroundColor=dialog_background_color)
        css.QLabel.setValues(backgroundColor=dialog_background_color)
        self.setStyleSheet(str(css))
コード例 #5
0
ファイル: undo_redo.py プロジェクト: s40723103/Pyslvs-UI
 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)
コード例 #6
0
def graph2icon(
    g: Graph,
    width: int,
    node_mode: bool,
    show_label: bool,
    monochrome: bool,
    *,
    except_node: Optional[int] = None,
    engine: str = "",
    pos: Optional[_Pos] = None
) -> QIcon:
    """Draw a generalized chain graph."""
    if engine:
        pos = engine_picker(g, engine, node_mode)
    if pos is None:
        raise ValueError("no engine selected")
    if not pos:
        pixmap = QPixmap(width, width)
        pixmap.fill(Qt.transparent)
        return QIcon(pixmap)

    width_bound = -float('inf')
    for x, y in pos.values():
        if abs(x) > width_bound:
            width_bound = x
        if abs(y) > width_bound:
            width_bound = y
    width_bound *= 2.5
    image = QImage(
        QSize(int(width_bound), int(width_bound)),
        QImage.Format_ARGB32_Premultiplied
    )
    image.fill(Qt.transparent)
    painter = QPainter(image)
    painter.translate(image.width() / 2, image.height() / 2)
    pen = QPen()
    r = int(width_bound / 50)
    pen.setWidth(r)
    painter.setPen(pen)
    _font.setPixelSize(r * 6)
    painter.setFont(_font)

    # Draw edges
    if node_mode:
        for l1, l2 in g.edges:
            if except_node in {l1, l2}:
                pen.setColor(Qt.gray)
            else:
                pen.setColor(Qt.black)
            painter.setPen(pen)
            painter.drawLine(pos[l1][0], -pos[l1][1], pos[l2][0], -pos[l2][1])
    else:
        color = color_qt('dark-gray') if monochrome else LINK_COLOR
        color.setAlpha(150)
        painter.setBrush(QBrush(color))
        for link in g.vertices:
            if link == except_node:
                pen.setColor(Qt.gray)
            else:
                pen.setColor(Qt.black)
            painter.setPen(pen)

            painter.drawPolygon(*convex_hull([
                (pos[n][0], -pos[n][1])
                for n, edge in edges_view(g) if link in edge
            ], as_qpoint=True))

    # Draw vertices
    for k, (x, y) in pos.items():
        if node_mode:
            color = color_num(len(list(g.neighbors(k))) - 1)
            if k == except_node:
                color.setAlpha(150)
        else:
            if monochrome:
                color = Qt.black
            elif except_node in dict(edges_view(g))[k]:
                color = color_qt('green')
            else:
                color = color_qt('blue')
        pen.setColor(color)
        painter.setPen(pen)
        painter.setBrush(QBrush(color))
        point = QPointF(x, -y)
        painter.drawEllipse(point, r, r)
        if show_label:
            pen.setColor(Qt.darkMagenta)
            painter.setPen(pen)
            painter.drawText(point, str(k))
    painter.end()
    return QIcon(QPixmap.fromImage(image).scaledToWidth(width))
コード例 #7
0
ファイル: home.py プロジェクト: fisher2017/Anaconda
    def __init__(self, parent=None):
        super(HomeTab, self).__init__(parent)

        # Variables
        self._parent = parent
        self.api = AnacondaAPI()
        self.setObjectName('Tab')

        # Widgetsugh
        main_icon = QLabel()
        self.list_applications = ListWidgetApplication()
        self.apps_model = None
        self.apps = None
        self.app_timers = None
        self.button_refresh = ButtonHomeRefresh('Refresh')
        self.frame_home = FrameHome(self)
        self.frame_home_top = FrameHomeTop(self)
        self.frame_home_bottom = FrameHomeTop(self)
        self.label_home = LabelHome('')
        self.label_status = QLabel('')
        self.timer_refresh = QTimer()

        # Widget setup
        pixmap = QPixmap(images.ANACONDA_ICON_128_PATH)
        main_icon.setPixmap(pixmap)
        main_text = ('My Applications')
        self.label_home.setText(main_text)
        self.list_applications.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        # Layout
        home_layout_top = QHBoxLayout()
        home_layout_top.addWidget(self.label_home, 10, Qt.AlignLeft)
        home_layout_top.addWidget(self.button_refresh, 1,
                                  Qt.AlignRight | Qt.AlignBottom)
        home_layout_top.setSpacing(0)
        self.frame_home_top.setLayout(home_layout_top)

        home_layout_bottom = QVBoxLayout()
        home_layout_bottom.addWidget(self.list_applications)
        home_layout_bottom.addWidget(self.label_status)
        home_layout_bottom.setSpacing(0)
        self.frame_home_bottom.setLayout(home_layout_bottom)

        home_layout = QVBoxLayout()
        home_layout.addWidget(self.frame_home_top)
        home_layout.addWidget(self.frame_home_bottom)
        home_layout.setSpacing(0)
        self.frame_home.setLayout(home_layout)

        layout = QHBoxLayout()
        layout.addWidget(self.frame_home)
        layout.setSpacing(0)
        self.setLayout(layout)

        # Signals
        self.list_applications.sig_application_updated.connect(
            self.sig_application_updated)
        self.list_applications.sig_application_updated.connect(
            self.update_list)
        self.list_applications.sig_status_updated.connect(self.update_status)
        self.button_refresh.clicked.connect(self.refresh_cards)
コード例 #8
0
 def showFileDialog(self):
     # 第二引数はダイアログのタイトル、第三引数は表示するパス
     fname = QFileDialog.getOpenFileName(self, u'画像ファイル選択', "C:/")
     pixmap = QPixmap(fname[0])
     self.image.setPixmap(pixmap)
コード例 #9
0
ファイル: utils.py プロジェクト: guiwitz/napari
def crosshair_pixmap():
    """Create a cross cursor with white/black hollow square pixmap in the middle.
    For use as points cursor."""

    size = 25

    pixmap = QPixmap(QSize(size, size))
    pixmap.fill(Qt.transparent)
    painter = QPainter(pixmap)

    # Base measures
    width = 1
    center = 3  # Must be odd!
    rect_size = center + 2 * width
    square = rect_size + width * 4

    pen = QPen(Qt.white, 1)
    pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
    painter.setPen(pen)

    # # Horizontal rectangle
    painter.drawRect(0, (size - rect_size) // 2, size - 1, rect_size - 1)

    # Vertical rectangle
    painter.drawRect((size - rect_size) // 2, 0, rect_size - 1, size - 1)

    # Square
    painter.drawRect((size - square) // 2, (size - square) // 2, square - 1,
                     square - 1)

    pen = QPen(Qt.black, 2)
    pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
    painter.setPen(pen)

    # # Square
    painter.drawRect(
        (size - square) // 2 + 2,
        (size - square) // 2 + 2,
        square - 4,
        square - 4,
    )

    pen = QPen(Qt.black, 3)
    pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
    painter.setPen(pen)

    # # # Horizontal lines
    mid_vpoint = QPoint(2, size // 2)
    painter.drawLine(mid_vpoint,
                     QPoint(((size - center) // 2) - center + 1, size // 2))
    mid_vpoint = QPoint(size - 3, size // 2)
    painter.drawLine(mid_vpoint,
                     QPoint(((size - center) // 2) + center + 1, size // 2))

    # # # Vertical lines
    mid_hpoint = QPoint(size // 2, 2)
    painter.drawLine(QPoint(size // 2, ((size - center) // 2) - center + 1),
                     mid_hpoint)
    mid_hpoint = QPoint(size // 2, size - 3)
    painter.drawLine(QPoint(size // 2, ((size - center) // 2) + center + 1),
                     mid_hpoint)

    painter.end()
    return pixmap
コード例 #10
0
    def __init__(self, parent):
        """Create About Spyder dialog with general information."""

        QDialog.__init__(self, parent)
        versions = get_versions()
        # Show Git revision for development version
        revlink = ''
        if versions['revision']:
            rev = versions['revision']
            revlink = " (<a href='https://github.com/spyder-ide/spyder/" \
                      "commit/%s'>Commit: %s</a>)" % (rev, rev)

        # Get current font properties
        font = self.font()
        font_family = font.family()
        font_size = font.pointSize()
        if sys.platform == 'darwin':
            font_size -= 2

        self.label = QLabel(
            _("""
            <div style='font-family: "{font_family}";
                        font-size: {font_size}pt;
                        font-weight: normal;
                        '>
            <p>
            <b>Spyder {spyder_ver}</b> {revision}
            <br>
            The Scientific Python Development Environment |
            <a href="{website_url}">Spyder-IDE.org</a>
            <br>
            Copyright &copy; 2009-2020 Spyder Project Contributors and
            <a href="{github_url}/blob/master/AUTHORS.txt">others</a>.
            <br>
            Distributed under the terms of the
            <a href="{github_url}/blob/master/LICENSE.txt">MIT License</a>.
            </p>
            <p>
            Created by Pierre Raybaut; current maintainer is Carlos Cordoba.
            Developed by the
            <a href="{github_url}/graphs/contributors">international
            Spyder community</a>. Many thanks to all the Spyder beta testers
            and dedicated users.
            </p>
            <p>For help with Spyder errors and crashes, please read our
            <a href="{trouble_url}">Troubleshooting Guide</a>, and for bug
            reports and feature requests, visit our
            <a href="{github_url}">Github site</a>. For project discussion,
            see our <a href="{forum_url}">Google Group</a>.
            </p>
            <p>
            This project is part of a larger effort to promote and
            facilitate the use of Python for scientific and engineering
            software development.
            The popular Python distributions
            <a href="https://www.anaconda.com/download/">Anaconda</a> and
            <a href="https://winpython.github.io/">WinPython</a>
            also contribute to this plan.
            </p>
            <p>
            Python {python_ver} {bitness}-bit | Qt {qt_ver} |
            {qt_api} {qt_api_ver} | {os_name} {os_ver}
            </p>
            <p><small>Certain source files under other compatible permissive
            licenses and/or originally by other authors.
            Spyder 3 theme icons derived from
            <a href="https://fontawesome.com/">Font Awesome</a> 4.7
            (&copy; 2016 David Gandy; SIL OFL 1.1) and
            <a href="http://materialdesignicons.com/">Material Design</a>
            (&copy; 2014 Austin Andrews; SIL OFL 1.1).
            Most Spyder 2 theme icons sourced from the
            <a href="https://www.everaldo.com">Crystal Project iconset</a>
            (&copy; 2006-2007 Everaldo Coelho; LGPL 2.1+).
            Other icons from
            <a href="http://p.yusukekamiyamane.com/">Yusuke Kamiyamane</a>
            (&copy; 2013 Yusuke Kamiyamane; CC-BY 3.0),
            the <a href="http://www.famfamfam.com/lab/icons/silk/">FamFamFam
            Silk icon set</a> 1.3 (&copy; 2006 Mark James; CC-BY 2.5), and
            the <a href="https://www.kde.org/">KDE Oxygen icons</a>
            (&copy; 2007 KDE Artists; LGPL 3.0+).</small>
            </p>
            <p>
            See the <a href="{github_url}/blob/master/NOTICE.txt">NOTICE</a>
            file for full legal information.
            </p>
            </div>
            """.format(
                spyder_ver=versions['spyder'],
                revision=revlink,
                website_url=__website_url__,
                github_url=__project_url__,
                trouble_url=__trouble_url__,
                forum_url=__forum_url__,
                python_ver=versions['python'],
                bitness=versions['bitness'],
                qt_ver=versions['qt'],
                qt_api=versions['qt_api'],
                qt_api_ver=versions['qt_api_ver'],
                os_name=versions['system'],
                os_ver=versions['release'],
                font_family=font_family,
                font_size=font_size,
            )))
        self.label.setWordWrap(True)
        self.label.setAlignment(Qt.AlignTop)
        self.label.setOpenExternalLinks(True)

        if is_dark_interface():
            icon_filename = "spyder.svg"
        else:
            icon_filename = "spyder_dark.svg"

        pixmap = QPixmap(get_image_path(icon_filename))
        self.label_pic = QLabel(self)
        self.label_pic.setPixmap(pixmap.scaled(64, 64))
        self.label_pic.setAlignment(Qt.AlignTop)

        btn = QPushButton(_("Copy to clipboard"), )
        bbox = QDialogButtonBox(QDialogButtonBox.Ok)

        # Widget setup
        self.setWindowIcon(ima.icon('tooloptions'))
        self.setModal(False)

        # Layout
        tophlayout = QHBoxLayout()
        tophlayout.addWidget(self.label_pic)
        tophlayout.addWidget(self.label)

        btmhlayout = QHBoxLayout()
        btmhlayout.addWidget(btn)
        btmhlayout.addStretch()
        btmhlayout.addWidget(bbox)

        vlayout = QVBoxLayout()
        vlayout.addLayout(tophlayout)
        vlayout.addLayout(btmhlayout)

        self.setLayout(vlayout)
        self.setFixedSize(410, 560)

        # Signals
        btn.clicked.connect(self.copy_to_clipboard)
        bbox.accepted.connect(self.accept)
コード例 #11
0
# -----------------------------------------------------------------------------

atexit.register(qCleanupResources)


def _get_splash_image_name():
    # gets the width of the screen where the main window was initialised
    width = QGuiApplication.primaryScreen().size().width()

    if width > 2048:
        return ':/images/MantidSplashScreen_4k.jpg'
    else:
        return ':/images/MantidSplashScreen.png'


SPLASH = QSplashScreen(QPixmap(_get_splash_image_name()),
                       Qt.WindowStaysOnTopHint)
SPLASH.show()
SPLASH.showMessage("Starting...", Qt.AlignBottom | Qt.AlignLeft
                   | Qt.AlignAbsolute, QColor(Qt.black))
# The event loop has not started - force event processing
QApplication.processEvents(QEventLoop.AllEvents)


# -----------------------------------------------------------------------------
# MainWindow
# -----------------------------------------------------------------------------


class MainWindow(QMainWindow):
    DOCKOPTIONS = QMainWindow.AllowTabbedDocks | QMainWindow.AllowNestedDocks
コード例 #12
0
ファイル: bts.py プロジェクト: pnallin/pydm-opi
    def __init__(self, parent=None, args=[], macros=None):
        super(BTS, self).__init__(parent=parent, args=args, macros=macros)

        self.label_pic.setPixmap(QPixmap(BTS_IMG))
コード例 #13
0
 def func() -> None:
     self.alignment_mode = m
     self.alignment_button.setIcon(QIcon(QPixmap(icon_name)))
コード例 #14
0
    def __appearance(self) -> None:
        """Start up and initialize custom widgets."""
        # Entities tables
        tab_bar = self.entities_tab.tabBar()
        tab_bar.setStatusTip("Switch the tabs to change to another view mode.")
        self.entities_point = PointTableWidget(self.entities_point_widget)
        self.entities_point.cellDoubleClicked.connect(self.edit_point)
        self.entities_point.delete_request.connect(self.delete_selected_points)
        self.entities_point_layout.addWidget(self.entities_point)
        self.entities_link = LinkTableWidget(self.entities_link_widget)
        self.entities_link.cellDoubleClicked.connect(self.edit_link)
        self.entities_link.delete_request.connect(self.delete_selected_links)
        self.entities_link_layout.addWidget(self.entities_link)
        self.entities_expr = ExprTableWidget(self.EntitiesExpr_widget)
        self.entities_expr_layout.insertWidget(0, self.entities_expr)
        self.__tables = (
            self.entities_point,
            self.entities_link,
            self.entities_expr,
        )

        # Select all button on the Point and Link tab as corner widget
        select_all_button = QPushButton()
        select_all_button.setIcon(QIcon(QPixmap(":/icons/select_all.png")))
        select_all_button.setToolTip("Select all")
        select_all_button.setStatusTip("Select all item of point table.")

        @Slot()
        def table_select_all() -> None:
            """Distinguish table by tab index."""
            self.__tables[self.entities_tab.currentIndex()].selectAll()

        select_all_button.clicked.connect(table_select_all)
        self.entities_tab.setCornerWidget(select_all_button)
        select_all_action = QAction("Select all point", self)
        select_all_action.triggered.connect(table_select_all)
        select_all_action.setShortcut("Ctrl+A")
        select_all_action.setShortcutContext(Qt.WindowShortcut)
        self.addAction(select_all_action)

        # QPainter canvas window
        self.main_canvas = MainCanvas(self)
        self.entities_tab.currentChanged.connect(
            self.main_canvas.set_selection_mode)
        select_tips = QLabel(self, Qt.ToolTip)

        @Slot(QPoint, str)
        def show_select_tips(pos: QPoint, text: str) -> None:
            select_tips.setText(text)
            select_tips.move(pos - QPoint(0, select_tips.height()))
            select_tips.show()

        self.main_canvas.selected_tips.connect(show_select_tips)
        self.main_canvas.selected_tips_hide.connect(select_tips.hide)

        @Slot(tuple, bool)
        def table_selection(selection: Sequence[int], check_key: bool) -> None:
            """Distinguish table by tab index."""
            index = self.entities_tab.currentIndex()
            self.__tables[index].set_selections(selection, check_key)

        self.main_canvas.selected.connect(table_selection)
        self.entities_point.row_selection_changed.connect(
            self.main_canvas.set_selection)

        @Slot()
        def table_clear_selection() -> None:
            """Clear the selection of specific table by tab index."""
            index = self.entities_tab.currentIndex()
            self.__tables[index].clearSelection()

        clean_selection_action = QAction("Clean selection", self)
        clean_selection_action.triggered.connect(table_clear_selection)
        clean_selection_action.setShortcut("Esc")
        clean_selection_action.setShortcutContext(Qt.WindowShortcut)
        self.main_canvas.no_selected.connect(table_clear_selection)
        self.addAction(clean_selection_action)

        self.main_canvas.free_moved.connect(self.set_free_move)
        self.main_canvas.alt_add.connect(self.add_point_by_pos)
        self.main_canvas.doubleclick_edit.connect(self.edit_point)
        self.main_canvas.zoom_changed.connect(self.zoom_bar.setValue)
        self.main_canvas.tracking.connect(self.set_mouse_pos)
        self.canvas_layout.insertWidget(0, self.main_canvas)
        self.canvas_splitter.setSizes([600, 10, 30])

        # Selection label on status bar right side
        selection_label = SelectionLabel(self)
        self.entities_point.selectionLabelUpdate.connect(
            selection_label.update_select_point)
        self.main_canvas.browse_tracking.connect(
            selection_label.update_mouse_position)
        self.status_bar.addPermanentWidget(selection_label)

        # FPS label on status bar right side
        fps_label = FPSLabel(self)
        self.main_canvas.fps_updated.connect(fps_label.update_text)
        self.status_bar.addPermanentWidget(fps_label)

        # Inputs widget
        self.inputs_widget = InputsWidget(self)
        self.inputs_tab_layout.addWidget(self.inputs_widget)
        self.free_move_button.toggled.connect(
            self.inputs_widget.variable_value_reset)
        self.inputs_widget.about_to_resolve.connect(self.resolve)

        @Slot(tuple, bool)
        def inputs_selection(selections: Sequence[int], _=None) -> None:
            """Distinguish table by tab index."""
            self.inputs_widget.clear_selection()
            if self.entities_tab.currentIndex() == 0:
                self.inputs_widget.set_selection(selections)

        self.main_canvas.selected.connect(inputs_selection)
        self.main_canvas.no_selected.connect(self.inputs_widget.clear_selection)
        self.inputs_widget.update_preview_button.clicked.connect(
            self.main_canvas.update_preview_path)

        # Synthesis collections
        self.collections = Collections(self)
        # Number and type synthesis
        self.structure_synthesis = StructureSynthesis(self)
        for widget, name in [
            (self.structure_synthesis, "Structural"),
            (self.collections, "Collections"),
        ]:  # type: QWidget, str
            self.synthesis_tab_widget.addTab(widget, widget.windowIcon(), name)

        # Dimensional synthesis
        self.dimensional_synthesis = DimensionalSynthesis(self)
        self.main_canvas.set_target_point.connect(
            self.dimensional_synthesis.set_point)
        self.synthesis_tab_widget.addTab(
            self.dimensional_synthesis,
            self.dimensional_synthesis.windowIcon(),
            "Dimensional"
        )
        # Same options of structure previews
        as_node1 = self.collections.structure_widget.graph_link_as_node
        as_node2 = self.structure_synthesis.graph_link_as_node
        as_node1.toggled.connect(as_node2.setChecked)
        as_node2.toggled.connect(as_node1.setChecked)
        show_label1 = self.collections.structure_widget.graph_show_label
        show_label2 = self.structure_synthesis.graph_show_label
        show_label1.toggled.connect(show_label2.setChecked)
        show_label2.toggled.connect(show_label1.setChecked)
        # File widget settings
        self.project_widget = ProjectWidget(self)
        self.project_layout.addWidget(self.project_widget)
        # Zooming and console dock will hide when startup
        self.zoom_widget.hide()
        self.console_widget.hide()
        # Connect to GUI button
        debug_mode = ARGUMENTS.debug_mode
        self.console_disconnect_button.setEnabled(not debug_mode)
        self.console_connect_button.setEnabled(debug_mode)
        # Splitter stretch factor
        self.main_splitter.setStretchFactor(0, 4)
        self.main_splitter.setStretchFactor(1, 15)
        self.mechanism_panel_splitter.setSizes([500, 200])
        # Enable mechanism menu actions when shows
        self.menu_mechanism.aboutToShow.connect(self.enable_mechanism_actions)
        # New main window function
        self.action_new_window.triggered.connect(self.new)
コード例 #15
0
    def _setupControlsWidget(self):
        ld_growenbl = QLabel('Grow/Damp Enable', self)
        cb_growenbl = PyDMEnumComboBox(self, self.dev_pref+':GDEN')

        ld_down = QLabel('Rec. Downsample ', self)
        sb_down = PyDMSpinbox(self, self.dev_pref+':'+self.TYPE+'_REC_DS')
        sb_down.showStepExponent = False

        ld_rawdata = QLabel('Raw Data', self)
        cb_rawdata = PyDMStateButton(self, self.dev_pref+':'+self.TYPE+'_DUMP')

        ld_acqtime = QLabel('Acquisition Time', self)
        sb_acqtime = PyDMSpinbox(self, self.dev_pref+':'+self.TYPE+'_ACQTIME')
        sb_acqtime.showStepExponent = False
        sb_acqtime.showUnits = True

        ld_holdoff = QLabel('Hold-Off Time', self)
        sb_holdoff = PyDMSpinbox(self, self.dev_pref+':'+self.TYPE+'_HOLDTIME')
        sb_holdoff.showStepExponent = False
        sb_holdoff.showUnits = True

        ld_posttrg = QLabel('Post Trigger', self)
        sb_posttrg = PyDMSpinbox(self, self.dev_pref+':'+self.TYPE+'_POSTTIME')
        sb_posttrg.showStepExponent = False
        sb_posttrg.showUnits = True
        fr_posttrg = SiriusFrame(
            self, self.dev_pref+':'+self.TYPE+'_POSTREG_SUBWR')
        fr_posttrg.add_widget(sb_posttrg)

        ld_growtime = QLabel('Growth Time', self)
        sb_growtime = PyDMSpinbox(self, self.dev_pref+':'+self.TYPE+'_GDTIME')
        sb_growtime.showStepExponent = False
        sb_growtime.showUnits = True
        fr_growtime = SiriusFrame(
            self, self.dev_pref+':'+self.TYPE+'_GDREG_SUBWR')
        fr_growtime.add_widget(sb_growtime)

        ld_acqlen = QLabel('Acquisition Length', self)
        lb_acqlen = PyDMLabel(self, self.dev_pref+':'+self.TYPE+'_ACQ_TURNS')
        lb_acqlen.showUnits = True

        ld_psttrglen = QLabel('Post Trigger Length', self)
        lb_psttrglen = PyDMLabel(
            self, self.dev_pref+':'+self.TYPE+'_POST_TURNS')
        lb_psttrglen.showUnits = True

        bt_modal = QPushButton('Modal Analysis', self)

        window = create_window_from_widget(
            _BbBModalAnalysis, title='SRAM Modal Analysis',
            icon=get_bbb_icon(), is_main=True)
        connect_window(
            bt_modal, window, self, prefix=self._prefix,
            device=self._device, acq_type=self.TYPE)

        gbox_dtacq = QGroupBox('Data Acquisition', self)
        lay_dtacq = QGridLayout(gbox_dtacq)
        lay_dtacq.addWidget(ld_growenbl, 0, 0)
        lay_dtacq.addWidget(cb_growenbl, 0, 1)
        lay_dtacq.addWidget(ld_down, 1, 0)
        lay_dtacq.addWidget(sb_down, 1, 1)
        lay_dtacq.addWidget(ld_rawdata, 2, 0)
        lay_dtacq.addWidget(cb_rawdata, 2, 1)
        lay_dtacq.addWidget(ld_acqtime, 3, 0)
        lay_dtacq.addWidget(sb_acqtime, 3, 1)
        lay_dtacq.addWidget(ld_holdoff, 4, 0)
        lay_dtacq.addWidget(sb_holdoff, 4, 1)
        lay_dtacq.addWidget(ld_posttrg, 5, 0)
        lay_dtacq.addWidget(fr_posttrg, 5, 1)
        lay_dtacq.addWidget(ld_growtime, 6, 0)
        lay_dtacq.addWidget(fr_growtime, 6, 1)
        lay_dtacq.addWidget(ld_acqlen, 7, 0)
        lay_dtacq.addWidget(lb_acqlen, 7, 1)
        lay_dtacq.addWidget(ld_psttrglen, 8, 0)
        lay_dtacq.addWidget(lb_psttrglen, 8, 1)
        lay_dtacq.addWidget(bt_modal, 9, 0, 1, 2)

        ld_acqtyp = QLabel(
            '<h4>Acq Type</h4>', self, alignment=Qt.AlignCenter)
        cb_acqtyp = PyDMEnumComboBox(
            self, self.dev_pref+':'+self.TYPE+'_POSTSEL')

        gbox_acqtyp = QGroupBox(self)
        lay_acqtyp = QVBoxLayout(gbox_acqtyp)
        lay_acqtyp.addWidget(ld_acqtyp)
        lay_acqtyp.addWidget(cb_acqtyp)

        ld_trgexten = QLabel('Internal/External', self)
        cb_trgexten = PyDMEnumComboBox(
            self, self.dev_pref+':'+self.TYPE+'_HWTEN')

        ld_trginsel = QLabel('Selection', self)
        cb_trginsel = PyDMEnumComboBox(
            self, self.dev_pref+':'+self.TYPE+'_TRIG_IN_SEL')

        ld_trgarm = QLabel('Arm', self)
        cb_trgarm = PyDMStateButton(self, self.dev_pref+':'+self.TYPE+'_ARM')
        lb_armmon = SiriusLedState(
            self, self.dev_pref+':'+self.TYPE+'_ARM_MON')

        ld_trgbrarm = QLabel('Auto re-arm', self)
        cb_trgbrarm = PyDMStateButton(
            self, self.dev_pref+':'+self.TYPE+'_BR_ARM')

        ld_rst = QLabel('Trigger 1/2 Cap.:', self)
        lb_rst1 = PyDMLabel(self, self.dev_pref+':'+self.TYPE+'_CAP_TRIG1')
        lb_rst2 = PyDMLabel(self, self.dev_pref+':'+self.TYPE+'_CAP_TRIG2')

        gbox_trig = QGroupBox('Trigger', self)
        lay_trig = QGridLayout(gbox_trig)
        lay_trig.setAlignment(Qt.AlignTop)
        lay_trig.addWidget(ld_trgexten, 0, 0)
        lay_trig.addWidget(cb_trgexten, 0, 1, 1, 2)
        lay_trig.addWidget(ld_trginsel, 1, 0)
        lay_trig.addWidget(cb_trginsel, 1, 1, 1, 2)
        lay_trig.addWidget(ld_trgarm, 2, 0)
        lay_trig.addWidget(cb_trgarm, 2, 1)
        lay_trig.addWidget(lb_armmon, 2, 2)
        lay_trig.addWidget(ld_trgbrarm, 3, 0)
        lay_trig.addWidget(cb_trgbrarm, 3, 1)
        lay_trig.addWidget(ld_rst, 4, 0)
        lay_trig.addWidget(lb_rst1, 4, 1)
        lay_trig.addWidget(lb_rst2, 4, 2)
        lay_trig.setRowStretch(5, 2)

        pixmap = QPixmap(_os.path.join(
            _os.path.abspath(_os.path.dirname(__file__)), 'grow_damp.png'))
        img_wid = QLabel(self)
        img_wid.setPixmap(pixmap)
        img_wid.setScaledContents(True)

        wid = QWidget()
        lay = QGridLayout(wid)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(gbox_acqtyp, 0, 0)
        lay.addWidget(gbox_dtacq, 1, 0)
        lay.addWidget(gbox_trig, 2, 0)
        lay.addWidget(img_wid, 4, 0)
        lay.setRowStretch(3, 5)
        lay.setRowStretch(5, 5)

        wid.setStyleSheet("SiriusFrame{max-height: 1.8em;}")

        return wid
コード例 #16
0
ファイル: components.py プロジェクト: swipswaps/vidify
 def setup_icon(self, icon: str) -> None:
     self.icon = QPixmap(icon)
     self.icon_label = QLabel()
     self.icon_label.setPixmap(self.icon)
     self.icon_label.setAlignment(Qt.AlignHCenter)
     self.layout.addWidget(self.icon_label)
コード例 #17
0
ファイル: community.py プロジェクト: amccarty/ac0n3
    def __init__(self,
                 parent=None,
                 tags=None,
                 content_urls=None,
                 content_path=CONTENT_PATH,
                 image_path=IMAGE_DATA_PATH,
                 config=CONF,
                 bundle_path=LINKS_INFO_PATH,
                 saved_content_path=CONTENT_JSON_PATH,
                 tab_name=''):
        """Community tab."""
        super(CommunityTab, self).__init__(parent=parent)

        self._tab_name = ''
        self.content_path = content_path
        self.image_path = image_path
        self.bundle_path = bundle_path
        self.saved_content_path = saved_content_path
        self.config = config

        self._parent = parent
        self._downloaded_thumbnail_urls = []
        self._downloaded_urls = []
        self._downloaded_filepaths = []
        self.api = AnacondaAPI()
        self.content_urls = content_urls
        self.content_info = []
        self.step = 0
        self.step_size = 1
        self.tags = tags
        self.timer_load = QTimer()
        self.pixmaps = {}
        self.filter_widgets = []
        self.default_pixmap = QPixmap(VIDEO_ICON_PATH).scaled(
            100, 60, Qt.KeepAspectRatio, Qt.FastTransformation)

        # Widgets
        self.text_filter = LineEditSearch()
        self.list = ListWidgetContent()
        self.frame_header = FrameTabHeader()
        self.frame_content = FrameTabContent()

        # Widget setup
        self.timer_load.setInterval(333)
        self.list.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.text_filter.setPlaceholderText('Search')
        self.text_filter.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.setObjectName("Tab")

        self.list.setMinimumHeight(200)
        fm = self.text_filter.fontMetrics()
        self.text_filter.setMaximumWidth(fm.width('M' * 23))

        # Layouts
        self.filters_layout = QHBoxLayout()

        layout_header = QHBoxLayout()
        layout_header.addLayout(self.filters_layout)
        layout_header.addStretch()
        layout_header.addWidget(self.text_filter)
        self.frame_header.setLayout(layout_header)

        layout_content = QHBoxLayout()
        layout_content.addWidget(self.list)
        self.frame_content.setLayout(layout_content)

        layout = QVBoxLayout()
        layout.addWidget(self.frame_header)
        layout.addWidget(self.frame_content)
        self.setLayout(layout)

        # Signals
        self.timer_load.timeout.connect(self.set_content_list)
        self.text_filter.textChanged.connect(self.filter_content)
コード例 #18
0
            button.setSizePolicy(sp)
            button.clicked.connect(index.data())

            self._parent.setIndexWidget(index, button)


class DisableDelegate(QItemDelegate):
    def __init__(self, parent):
        super(DisableDelegate, self).__init__(parent)
        self._parent = parent

    def paint(self, painter, option, index):
        if not self._parent.indexWidget(index):
            button = QToolButton(self.parent())
            button.setText("i")
            button.setAutoRaise(True)

            button.setIcon(enableicon)
            button.setCheckable(True)
            sp = QSizePolicy()
            sp.setWidthForHeight(True)
            button.setSizePolicy(sp)
            button.clicked.connect(index.data())

            self._parent.setIndexWidget(index, button)


enableicon = QIcon()
enableicon.addPixmap(QPixmap(path("icons/enable.png")), state=enableicon.Off)
enableicon.addPixmap(QPixmap(path("icons/disable.png")), state=enableicon.On)
コード例 #19
0
ファイル: iconic_font.py プロジェクト: stonebig/qtawesome
 def pixmap(self, size, mode, state):
     pm = QPixmap(size)
     pm.fill(Qt.transparent)
     self.paint(QPainter(pm), QRect(QPoint(0, 0), size), mode, state)
     return pm
コード例 #20
0
def create_icon(icon_path: str = ":/pyqt/source/images/New.png"):
    icon = QIcon()
    icon.addPixmap(QPixmap(icon_path), QIcon.Normal, QIcon.Off)
    return icon
コード例 #21
0
 def __plot(self) -> None:
     """Plot the data. Show the X and Y axises as two line."""
     joint = self.plot_joint.currentIndex()
     name = self.__current_path_name()
     data = self.__paths.get(name, [])
     slider_data = self.__slider_paths.get(name, {})
     if not data:
         return
     if self.plot_joint_slot.isChecked():
         pos = array(slider_data.get(joint, []))
     else:
         pos = array(data[joint])
     if self.wrt_label.isChecked():
         joint_wrt = self.wrt_joint.currentIndex()
         if self.wrt_joint_slot.isChecked():
             pos[:] -= array(slider_data.get(joint_wrt, []))
         else:
             pos[:] -= array(data[joint_wrt])
     vel = derivative(pos)
     acc = derivative(vel)
     cur = curvature(data[joint])
     plot = {}
     plot_count = 0
     if self.plot_pos.isChecked():
         plot_count += 1
         plot["Position"] = pos
     if self.plot_vel.isChecked():
         plot_count += 1
         plot["Velocity"] = vel
     if self.plot_acc.isChecked():
         plot_count += 1
         plot["Acceleration"] = acc
     if self.plot_jerk.isChecked():
         plot_count += 1
         plot["Jerk"] = derivative(acc)
     if self.plot_curvature.isChecked():
         plot_count += 1
         plot["Curvature"] = cur
     if self.plot_signature.isChecked():
         plot_count += 1
         plot["Path Signature"] = path_signature(cur)
     if plot_count < 1:
         QMessageBox.warning(self, "No target", "No any plotting target.")
         return
     polar = self.p_coord_sys.isChecked()
     row = plot_count
     col = 1
     if polar:
         row, col = col, row
     dlg = DataChartDialog(self, "Analysis", row, col, polar)
     dlg.setWindowIcon(QIcon(QPixmap(":/icons/formula.png")))
     ax = dlg.ax()
     for p, (title, xy) in enumerate(plot.items()):
         ax_i = ax[p]
         ax_i.set_title(title)
         if title == "Path Signature":
             ax_i.plot(xy[:, 0], xy[:, 1])
             ax_i.set_ylabel(r"$\kappa$")
             ax_i.set_xlabel(r"$\int|\kappa|dt$")
         elif xy.ndim == 2:
             x = xy[:, 0]
             y = xy[:, 1]
             if self.c_coord_sys.isChecked():
                 ax_i.plot(x, label='x')
                 ax_i.plot(y, label='y')
                 ax_i.legend()
             else:
                 r = hypot(x, y)
                 theta = arctan2(y, x)
                 ax_i.plot(theta, r, linewidth=5)
         else:
             ax_i.plot(xy)
     dlg.set_margin(0.2)
     dlg.show()
     dlg.exec_()
     dlg.deleteLater()
コード例 #22
0
 def setup_command_link_button(self, link_button, text, image_location, width=40, height=40):
     link_button.setText(text)
     link_button.setIconSize(QSize(self.rescale_w(width), self.rescale_h(height)))
     link_button.setIcon(QIcon(QPixmap(image_location)))
     return link_button
コード例 #23
0
ファイル: undo_redo.py プロジェクト: s40723103/Pyslvs-UI
 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)
コード例 #24
0
    def __init__(self, viewer):
        super().__init__()

        QCoreApplication.setAttribute(
            Qt.AA_UseStyleSheetPropagationInWidgetStyles, True
        )

        self.viewer = viewer

        self.canvas = SceneCanvas(keys=None, vsync=True)
        self.canvas.native.setMinimumSize(QSize(100, 100))

        self.canvas.connect(self.on_mouse_move)
        self.canvas.connect(self.on_mouse_press)
        self.canvas.connect(self.on_mouse_release)
        self.canvas.connect(self.on_key_press)
        self.canvas.connect(self.on_key_release)
        self.canvas.connect(self.on_draw)

        self.view = self.canvas.central_widget.add_view()

        # Set 2D camera (the camera will scale to the contents in the scene)
        self.view.camera = PanZoomCamera(aspect=1)
        # flip y-axis to have correct aligment
        self.view.camera.flip = (0, 1, 0)
        self.view.camera.set_range()
        self.view.camera.viewbox_key_event = viewbox_key_event

        # TO DO: Remove
        self.viewer._view = self.view

        center = QWidget()
        center_layout = QVBoxLayout()
        center_layout.setContentsMargins(15, 20, 15, 10)
        center_layout.addWidget(self.canvas.native)
        self.dims = QtDims(self.viewer.dims)
        center_layout.addWidget(self.dims)
        center.setLayout(center_layout)

        # Add controls, center, and layerlist
        self.control_panel = QtControls(viewer)
        self.addWidget(self.control_panel)
        self.addWidget(center)

        right = QWidget()
        right_layout = QVBoxLayout()
        self.layers = QtLayerList(self.viewer.layers)
        right_layout.addWidget(self.layers)
        self.buttons = QtLayersButtons(viewer)
        right_layout.addWidget(self.buttons)
        right.setLayout(right_layout)
        right.setMinimumSize(QSize(308, 250))

        self.addWidget(right)

        self._last_visited_dir = str(Path.home())

        self._cursors = {
            'disabled': QCursor(
                QPixmap(':/icons/cursor/cursor_disabled.png').scaled(20, 20)
            ),
            'cross': Qt.CrossCursor,
            'forbidden': Qt.ForbiddenCursor,
            'pointing': Qt.PointingHandCursor,
            'standard': QCursor(),
        }

        self._update_palette(viewer.palette)

        self._key_release_generators = {}

        self.viewer.events.interactive.connect(self._on_interactive)
        self.viewer.events.cursor.connect(self._on_cursor)
        self.viewer.events.reset_view.connect(self._on_reset_view)
        self.viewer.events.palette.connect(
            lambda event: self._update_palette(event.palette)
        )
        self.viewer.layers.events.reordered.connect(self._update_canvas)

        self.setAcceptDrops(True)
コード例 #25
0
ファイル: qthelpers.py プロジェクト: ssciff/spyder
def get_image_label(name, default="not_found.png"):
    """Return image inside a QLabel object"""
    label = QLabel()
    label.setPixmap(QPixmap(get_image_path(name, default)))
    return label
コード例 #26
0
def png_to_qimage(png):
    """Return a QImage from the raw data of a png image."""
    qpix = QPixmap()
    qpix.loadFromData(png, 'image/png'.upper())
    return qpix.toImage()
コード例 #27
0
    INFO: "INFO",
    WARNING: "WARNING",
    ERROR: "ERROR",
    CRITICAL: "CRITICAL"
}

trayicon = None
if "qtpy" in sys.modules:
    from qtpy.QtWidgets import QApplication

    if QApplication.instance():
        from qtpy.QtWidgets import QSystemTrayIcon
        from qtpy.QtGui import QIcon, QPixmap
        from xicam.gui.static import path

        trayicon = QSystemTrayIcon(QIcon(QPixmap(str(
            path("icons/cpu.png")))))  # TODO: better icon

_thread_count = 0


def _increment_thread():
    global _thread_count
    _thread_count += 1
    return _thread_count


threadIds = defaultdict(_increment_thread)


def showProgress(value: int, minval: int = 0, maxval: int = 100):
    """
コード例 #28
0
 def invalidateBackingStore(self):
     """Invalidate the internal backing store"""
     if self.__data.backingStore:
         self.__data.backingStore = QPixmap()
コード例 #29
0
    def __init__(self):
        super(XicamMainWindow, self).__init__()

        # Set icon
        self.setWindowIcon(QIcon(QPixmap(str(path("icons/xicam.gif")))))

        # Set size and position
        self.setGeometry(0, 0, 1000, 600)
        frameGm = self.frameGeometry()
        screen = QApplication.desktop().screenNumber(
            QApplication.desktop().cursor().pos())
        centerPoint = QApplication.desktop().screenGeometry(screen).center()
        frameGm.moveCenter(centerPoint)
        self.move(frameGm.topLeft())

        # Init child widgets to None
        self.topwidget = (self.leftwidget) = (self.rightwidget) = (
            self.bottomwidget
        ) = self.lefttopwidget = self.righttopwidget = self.leftbottomwidget = self.rightbottomwidget = None

        # Setup appearance
        self.setWindowTitle("Xi-cam")
        self.load_style()

        # Attach an object to restore config when loaded
        self._config_restorer = ConfigRestorer()

        # Load plugins
        pluginmanager.qt_is_safe = True
        pluginmanager.initialize_types()
        pluginmanager.collect_plugins()

        # Setup center/toolbar/statusbar/progressbar
        self.pluginmodewidget = pluginModeWidget()
        self.pluginmodewidget.sigSetStage.connect(self.setStage)
        self.pluginmodewidget.sigSetGUIPlugin.connect(self.setGUIPlugin)
        self.addToolBar(self.pluginmodewidget)
        self.setStatusBar(QStatusBar(self))
        msg.progressbar = QProgressBar(self)
        msg.progressbar.hide()
        msg.statusbar = self.statusBar()
        self.statusBar().addPermanentWidget(msg.progressbar)
        self.setCentralWidget(QStackedWidget())
        # NOTE: CentralWidgets are force-deleted when replaced, even if the object is still referenced;
        # To avoid this, a QStackedWidget is used for the central widget.

        # Setup menubar
        menubar = DebuggableMenuBar()
        self.setMenuBar(menubar)
        file = QMenu("&File", parent=menubar)
        menubar.addMenu(file)
        file.addAction("Se&ttings",
                       self.showSettings,
                       shortcut=QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_S))
        file.addAction("E&xit", self.close)

        # Set up help
        help = QMenu("&Help", parent=menubar)
        documentation_link = QUrl("https://xi-cam.readthedocs.io/en/latest/")
        help.addAction("Xi-CAM &Help",
                       lambda: QDesktopServices.openUrl(documentation_link))
        slack_link = QUrl("https://nikea.slack.com")
        help.addAction("Chat on &Slack",
                       lambda: QDesktopServices.openUrl(slack_link))
        help.addSeparator()

        about_title = "About Xi-CAM"
        version_text = f"""Version: <strong>{version.get_versions()['version']}</strong>"""
        copyright_text = f"""<small>Copyright (c) 2016, The Regents of the University of California, \
            through Lawrence Berkeley National Laboratory \
            (subject to receipt of any required approvals from the U.S. Dept. of Energy). \
            All rights reserved.</small>"""
        funding_text = f"""Funding for this research was provided by: \
            Lawrence Berkeley National Laboratory (grant No. TReXS LDRD to AH); \
            US Department of Energy (award No. Early Career Award to AH; \
            contract No. DE-SC0012704; contract No. DE-AC02-06CH11357; \
            contract No. DE-AC02-76SF00515; contract No. DE-AC02-05CH11231); \
            Center for Advanced Mathematics in Energy Research Applications; \
            Light Source Directors Data Solution Task Force Pilot Project."""
        about_text = version_text + "<br><br>" + funding_text + "<br><hr>" + copyright_text
        about_box = QMessageBox(QMessageBox.NoIcon, about_title, about_text)
        about_box.setTextFormat(Qt.RichText)
        about_box.setWindowModality(Qt.NonModal)
        help.addAction("&About Xi-CAM", lambda: about_box.show())

        menubar.addMenu(help)

        # Initialize layout with first plugin
        self._currentGUIPlugin = None
        self.build_layout()

        # self._currentGUIPlugin = pluginmanager.getPluginsOfCategory("GUIPlugin")[0]
        self.populate_layout()

        # Make F key bindings
        fkeys = [
            Qt.Key_F1,
            Qt.Key_F2,
            Qt.Key_F3,
            Qt.Key_F4,
            Qt.Key_F5,
            Qt.Key_F6,
            Qt.Key_F7,
            Qt.Key_F8,
            Qt.Key_F9,
            Qt.Key_F10,
            Qt.Key_F11,
            Qt.Key_F12,
        ]
        self.Fshortcuts = [QShortcut(QKeySequence(key), self) for key in fkeys]
        for i in range(12):
            self.Fshortcuts[i].activated.connect(partial(self.setStage, i))

        self.readSettings()
        # Wireup default widgets
        get_default_stage()["left"].sigOpen.connect(self.open)
        get_default_stage()["left"].sigOpen.connect(print)
        get_default_stage()["left"].sigPreview.connect(
            get_default_stage()["lefttop"].preview)
コード例 #30
0
ファイル: videos.py プロジェクト: fisher2017/Anaconda
    def __init__(self,
                 title='',
                 description='',
                 uri='',
                 authors=[],
                 venue='',
                 path='',
                 year='',
                 summary='',
                 banner='',
                 tags='',
                 subtitle='',
                 date='',
                 pixmap=None):
        super(ListItemContent, self).__init__()

        self.title = title
        self.uri = uri
        self.authors = authors
        self.venue = venue
        self.banner = banner
        self.year = year
        self.path = path
        self.tags = tags
        self.subtitle = subtitle
        self.date = date
        self.summary = summary
        self.timer_pixmap = QTimer()
        self.pixmaps = {}
        self.pixmap = pixmap
        self.label = None

        # Widgets
        self.widget = WidgetContent()
        self.button_information = ButtonContentInformation('more...',
                                                           parent=self.widget)
        self.button_view = ButtonContent(parent=self.widget)
        self.label_icon = LabelContentIcon(parent=self.widget)
        self.label_text = LabelContentText(summary, parent=self.widget)

        # Widget setup
        valid_tags = [
            'documentation', 'webinar', 'event', 'video', 'training', 'forum',
            'social'
        ]
        tag = 'notag'
        if len(tags) >= 1:
            filter_tags = [t.lower() for t in tags if t.lower() in valid_tags]
            if filter_tags:
                tag = filter_tags[0].lower()

        self.button_view.setObjectName(tag)
        self.button_view.setText((wrapText(title, 3)))
        self.button_information.setObjectName(tag)
        self.label_icon.setAlignment(Qt.AlignCenter)
        self.label_text.setAlignment(Qt.AlignCenter)
        self.label_text.setWordWrap(True)
        self.timer_pixmap.setInterval(random.randint(950, 1050))
        if pixmap:
            self.label_icon.setPixmap(
                QPixmap(VIDEO_ICON_PATH).scaled(100, 60, Qt.KeepAspectRatio,
                                                Qt.FastTransformation))

        # Layout
        if title and uri:
            self.widget_layout = QVBoxLayout(self.widget)
            self.widget_layout.addWidget(self.label_icon, 0, Qt.AlignCenter)
            self.widget_layout.addWidget(self.button_view, 0, Qt.AlignCenter)
            self.widget_layout.addWidget(self.label_text, 0, Qt.AlignCenter)
            self.widget_layout.addWidget(self.button_information, 0,
                                         Qt.AlignRight)
            self.setSizeHint(QSize(180, 190))
            #            self.setSizeHint(QSize(180, 250))
            self.widget.setLayout(self.widget_layout)
        if summary:
            tt = ('<p><b>' + title + '</b></p><p>' + subtitle + '</p>'
                  '<p>' + date + '</p>' + '<div>' + summary + '</div>')
            self.label = LabelContentInformation(tt)

        if not self.label:
            self.button_information.setDisabled(True)

        # Signals
        self.button_information.clicked.connect(self.show_information)
        self.timer_pixmap.timeout.connect(self.update_thumbnail)

        # Setup
        self.timer_pixmap.start()