Exemple #1
0
 def createAction(self, name, text, icon=None, shortcut=None, method=None):
     action = QtGui.QAction(Window)
     action.setIcon(gui_utils.get_icon(icon))
     action.setObjectName(name)
     action.setText(text)
     action.setShortcut(shortcut)
     action.triggered.connect(method)
     return action
Exemple #2
0
    def __init__(self, fig=None, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setWindowTitle('TFS-Plotter')
        self.setWindowIcon(get_icon("photo"))

        self._create_logger()
        self._create_menu()

        self._create_main_frame(fig)
Exemple #3
0
    def __init__(self, fig=None, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setWindowTitle('TFS-Plotter')
        self.setWindowIcon(get_icon("photo"))

        self._create_logger()
        self._create_menu()

        self._create_main_frame(fig)
    def _init_toolbar(self):
        """ Called from the super function """
        self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images')

        for text, tooltip_text, image_file, callback in self.toolitems:
            if text is None:
                self.addSeparator()
            else:
                try:
                    icon = get_icon(image_file)
                except IOError:
                    icon = self._icon(image_file + '.png')

                a = self.addAction(icon,
                                   text, getattr(self, callback))
                self._actions[callback] = a
                if callback in ['zoom', 'pan']:
                    a.setCheckable(True)
                if tooltip_text is not None:
                    a.setToolTip(tooltip_text)
                if text == 'Subplots':
                    a = self.addAction(self._icon("qt4_editor_options.png"),
                                       'Customize', self.edit_parameters)
                    a.setToolTip('Edit axis, curve and image parameters')

        self.buttons = {}

        # Add the x,y location widget at the right side of the toolbar
        # The stretch factor is 1 which means any resizing of the toolbar
        # will resize this label instead of the buttons.
        if self.coordinates:
            self.locLabel = QtWidgets.QLabel("", self)
            self.locLabel.setAlignment(
                QtCore.Qt.AlignRight | QtCore.Qt.AlignTop)
            self.locLabel.setSizePolicy(
                QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                      QtWidgets.QSizePolicy.Ignored))
            labelAction = self.addWidget(self.locLabel)
            labelAction.setVisible(True)

        # reference holder for subplots_adjust window
        self.adj_window = None

        # Aesthetic adjustments - we need to set these explicitly in PyQt5
        # otherwise the layout looks different - but we don't want to set it if
        # not using HiDPI icons otherwise they look worse than before.

        self.setIconSize(QtCore.QSize(NavigationToolbar.ICON_SIZE, NavigationToolbar.ICON_SIZE))
        self.layout().setSpacing(12)
Exemple #5
0
def _show_form(props, title, parent):
    form = []
    for ppty in props:
        if isinstance(ppty, Property):
            # proper property
            form.append(ppty.get_form_line())
        elif isinstance(ppty, six.string_types):
            # tuple
            form.append((None, "<b>{}</b>".format(ppty)))
        else:
            # separator
            form.append((None, None))

    return formlayout.fedit(form, title=title, parent=parent, icon=get_icon('edit'),
                            apply=
                            lambda d, p=props, par=parent: _apply_data_to_properties(p, d, par)
                            )
Exemple #6
0
    def setupUi(self, MainWindow):
        self.window = MainWindow
        MainWindow.setObjectName("Window")
        MainWindow.resize(930, 480)
        MainWindow.closeEvent = self.closeEvent
        MainWindow.setWindowIcon(gui_utils.get_icon("icon"))
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.gridLayout = QtGui.QGridLayout(self.centralWidget)
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtGui.QLabel(self.centralWidget)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
                                       QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.label.sizePolicy().hasHeightForWidth())

        self.label.setSizePolicy(sizePolicy)
        self.label.setObjectName("label")
        self.label.setText(u"Кафедра")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)

        self.deptComboBox = QtGui.QComboBox(self.centralWidget)
        self.deptComboBox.setObjectName("deptComboBox")
        self.deptComboBox.activated[str].connect(self.setTable)
        self.deptComboBox.addItems([dept[1] for dept in self.depts])
        self.gridLayout.addWidget(self.deptComboBox, 0, 1, 1, 1)

        self.hardwareComboBox = QtGui.QComboBox(self.centralWidget)
        self.hardwareComboBox.setObjectName("hardwareComboBox")
        self.hardwareComboBox.activated[str].connect(self.setTable)
        self.hardwareComboBox.addItem(u"Все оборудование")
        self.hardwareComboBox.addItems([hard[0] for hard in self.hardware])
        self.gridLayout.addWidget(self.hardwareComboBox, 0, 2, 1, 1)

        self.table = QtGui.QTableWidget(self.centralWidget)
        self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.table.setAlternatingRowColors(True)
        self.table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        self.table.verticalHeader().setVisible(False)
        #self.table.horizontalHeader().setSortIndicatorShown(True)
        self.table.horizontalHeader().setHighlightSections(False)
        self.table.resizeColumnsToContents()
        self.table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)

        self.gridLayout.addWidget(self.table, 1, 0, 1, 3)
        MainWindow.setCentralWidget(self.centralWidget)

        MainWindow.setWindowTitle(u"Норма обеспеченности")

        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)

        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.toolBar = QtGui.QToolBar(MainWindow)
        self.toolBar.setMovable(False)
        self.toolBar.setIconSize(QtCore.QSize(32, 32))
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.toolBar.setFloatable(True)
        self.toolBar.setObjectName("toolBar")
        self.toolBar.setWindowTitle("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)

        self.importAction = QtGui.QAction(u"Импорт",
                                          MainWindow,
                                          shortcut="Ctrl+Shift+I",
                                          triggered=self.importAction)
        self.importAction = self.createAction("importAction", u"Импорт",
                                              "import", "Ctrl+Shift+I",
                                              self.importFromFile)
        self.exportAction = self.createAction("exportAction", u"Экспорт",
                                              "export", "Ctrl+Shift+E",
                                              self.exportToFile)
        self.exitAction = self.createAction("exitAction",
                                            u"Выход",
                                            method=MainWindow.close)

        self.copyAction = self.createAction("copyAction", u"Копировать",
                                            "copy", "Ctrl+C",
                                            self.copyToClipboard)
        self.copyRowAction = self.createAction("copyRowAction",
                                               u"Копировать строку",
                                               "table_select_row",
                                               "Ctrl+Shift+C",
                                               self.copyRowToClipboard)
        self.addEquipmentAction = self.createAction("addEquipmentAction",
                                                    u"Добавить",
                                                    "table_add",
                                                    method=self.addEquipment)
        self.delEquipmentAction = self.createAction("delEquipmentAction",
                                                    u"Удалить",
                                                    method=self.delEquipment)
        self.removeAllAction = self.createAction(
            "removeAllAction",
            u"Удалить оборудование кафедры",
            method=self.removeAll)

        self.configAction = self.createAction("configAction", u"Настройки...",
                                              "config", "Ctrl+,", self.config)

        self.globalTimesheeAction = self.createAction(
            "globalTimesheeAction",
            u"Табель обеспеченности академии",
            method=self.getGlobalTimesheet)
        self.equipmentsAction = self.createAction(
            "equipmentsAction",
            u"Материально-техническая база",
            method=self.getEquipments)
        self.backupAction = self.createAction("backupAction",
                                              u"Резервирование",
                                              "backup",
                                              method=self.backup)

        self.sqlSpyAction = self.createAction("sqlSpyAction",
                                              u"SQLiteSpy",
                                              method=self.runSQLiteSpy)
        self.vacuumAction = self.createAction("vacuumAction",
                                              u"Очистить БД",
                                              "refresh",
                                              method=self.vacuum)

        self.aboutAction = self.createAction("aboutAction",
                                             u"О программе...",
                                             method=self.about)

        self.searchAction = self.createAction("searchAction",
                                              u"Искать на Яндекс Маркете",
                                              method=self.search)

        self.fileMenu = self.createMenuItem("fileMenu", u"Файл", [
            self.importAction, self.exportAction, self.exitAction,
            self.createSeparator(), self.exitAction
        ])
        self.menubar.addAction(self.fileMenu.menuAction())

        self.editMenu = self.createMenuItem("editMenu", u"Правка", [
            self.copyAction, self.copyRowAction,
            self.createSeparator(), self.addEquipmentAction,
            self.delEquipmentAction, self.removeAllAction,
            self.createSeparator(), self.configAction
        ])
        self.menubar.addAction(self.editMenu.menuAction())

        self.reportMenu = self.createMenuItem(
            "reportMenu", u"Отчеты",
            [self.globalTimesheeAction, self.equipmentsAction])
        self.menubar.addAction(self.reportMenu.menuAction())

        self.toolsMenu = self.createMenuItem(
            "toolsMenu", u"Инструменты",
            [self.vacuumAction, self.sqlSpyAction])
        self.menubar.addAction(self.toolsMenu.menuAction())

        self.helpMenu = self.createMenuItem("helpMenu", u"Справка",
                                            [self.aboutAction])
        self.menubar.addAction(self.helpMenu.menuAction())

        self.toolBar.addActions([
            self.importAction, self.exportAction, self.addEquipmentAction,
            self.configAction, self.backupAction
        ])

        self.setTable()
Exemple #7
0
def figure_edit(axes, parent=None):
    """Edit matplotlib figure options"""
    sep = (None, None)  # separator

    # Get / General
    # Cast to builtin floats as they have nicer reprs.
    xmin, xmax = map(float, axes.get_xlim())
    ymin, ymax = map(float, axes.get_ylim())
    general = [('Title', axes.get_title()),
               sep,
               (None, "<b>X-Axis</b>"),
               ('Left', xmin), ('Right', xmax),
               ('Label', axes.get_xlabel()),
               ('Scale', [axes.get_xscale(), 'linear', 'log', 'logit']),
               sep,
               (None, "<b>Y-Axis</b>"),
               ('Bottom', ymin), ('Top', ymax),
               ('Label', axes.get_ylabel()),
               ('Scale', [axes.get_yscale(), 'linear', 'log', 'logit']),
               sep,
               ('(Re-)Generate automatic legend', False),
               ]

    # Save the unit data
    xconverter = axes.xaxis.converter
    yconverter = axes.yaxis.converter
    xunits = axes.xaxis.get_units()
    yunits = axes.yaxis.get_units()

    # Sorting for default labels (_lineXXX, _imageXXX).
    def cmp_key(label):
        match = re.match(r"(_line|_image)(\d+)", label)
        if match:
            return match.group(1), int(match.group(2))
        else:
            return label, 0

    # Get / Curves
    linedict = {}
    for line in axes.get_lines():
        label = line.get_label()
        if label == NOLEGEND:
            continue
        linedict[label] = line

    for idx, ebar in enumerate([cont for cont in axes.containers if outils.is_errorbar(cont)]):
            label = ebar.get_label()
            if label is None:
                label = ""
            elif label == NOLEGEND:
                label = "unnamed{:d}".format(idx)
            linedict[label] = ebar

    curves = []

    curvelabels = sorted(linedict, key=cmp_key)
    for label in curvelabels:
        line = linedict[label]
        if outils.is_errorbar(line):
            line = line[0]

        color = mcolors.to_hex(
            mcolors.to_rgba(line.get_color(), line.get_alpha()),
            keep_alpha=True)
        ec = mcolors.to_hex(
            mcolors.to_rgba(line.get_markeredgecolor(), line.get_alpha()),
            keep_alpha=True)
        fc = mcolors.to_hex(
            mcolors.to_rgba(line.get_markerfacecolor(), line.get_alpha()),
            keep_alpha=True)
        ls_data = outils.prepare_formdata(LINESTYLES, line.get_linestyle())
        ds_data = outils.prepare_formdata(DRAWSTYLES, line.get_drawstyle())
        ms_data = outils.prepare_formdata(MARKERS, line.get_marker())
        curvedata = [
            ('Label', label),
            ('Visible', line.get_visible()),
            sep,
            (None, '<b>Line</b>'),
            ('Line style', [ls_data[0]] + ls_data[1]),
            ('Draw style', [ds_data[0]] + ds_data[1]),
            ('Width', line.get_linewidth()),
            ('Color (RGBA)', color),
            sep,
            (None, '<b>Marker</b>'),
            ('Style', [ms_data[0]] + ms_data[1]),
            ('Size', line.get_markersize()),
            ('Face color (RGBA)', fc),
            ('Edge color (RGBA)', ec),
        ]

        curves.append([curvedata, label, ""])
    # Is there a curve displayed?
    has_curve = bool(curves)

    # Get / Images
    imagedict = {}
    for image in axes.get_images():
        label = image.get_label()
        if label == NOLEGEND:
            continue
        imagedict[label] = image
    imagelabels = sorted(imagedict, key=cmp_key)
    images = []
    cmaps = [(cmap, name) for name, cmap in sorted(cm.cmap_d.items())]
    for label in imagelabels:
        image = imagedict[label]
        cmap = image.get_cmap()
        if cmap not in cm.cmap_d.values():
            cmaps = [(cmap, cmap.name)] + cmaps
        low, high = image.get_clim()
        imagedata = [
            ('Label', label),
            ('Colormap', [cmap.name] + cmaps),
            ('Min. value', low),
            ('Max. value', high),
            ('Interpolation',
             [image.get_interpolation()]
             + [(name, name) for name in sorted(mimage.interpolations_names)])]
        images.append([imagedata, label, ""])
    # Is there an image displayed?
    has_image = bool(images)

    datalist = [(general, "Axes", "")]
    if curves:
        datalist.append((curves, "Curves", ""))
    if images:
        datalist.append((images, "Images", ""))

    def apply_callback(data):
        """This function will be called to apply changes"""
        orig_xlim = axes.get_xlim()
        orig_ylim = axes.get_ylim()

        general = data.pop(0)
        curves = data.pop(0) if has_curve else []
        images = data.pop(0) if has_image else []
        if data:
            raise ValueError("Unexpected field")

        # Set / General
        (title, xmin, xmax, xlabel, xscale, ymin, ymax, ylabel, yscale,
         generate_legend) = general

        if axes.get_xscale() != xscale:
            axes.set_xscale(xscale)
        if axes.get_yscale() != yscale:
            axes.set_yscale(yscale)

        axes.set_title(title)
        axes.set_xlim(xmin, xmax)
        axes.set_xlabel(xlabel)
        axes.set_ylim(ymin, ymax)
        axes.set_ylabel(ylabel)

        # Restore the unit data
        axes.xaxis.converter = xconverter
        axes.yaxis.converter = yconverter
        axes.xaxis.set_units(xunits)
        axes.yaxis.set_units(yunits)
        axes.xaxis._update_axisinfo()
        axes.yaxis._update_axisinfo()

        # Set / Curves
        for index, curve in enumerate(curves):
            (label, visible, linestyle, drawstyle, linewidth, color, marker, markersize,
             markerfacecolor, markeredgecolor) = curve

            line = linedict[curvelabels[index]]
            hbar = None
            vbar = None
            ebar = None
            line.set_label(label)

            if outils.is_errorbar(line):
                ebar = line
                hbar = ebar[1]
                vbar = ebar[2]
                line = ebar[0]

            line.set_linestyle(linestyle)
            line.set_drawstyle(drawstyle)
            line.set_linewidth(linewidth)
            rgba = mcolors.to_rgba(color)
            line.set_alpha(None)
            line.set_color(rgba)
            line.set_visible(visible)
            for bar in [hbar, vbar]:
                if bar is not None:
                    for b in bar:
                        b.set_linewidth(linewidth)
                        b.set_color(rgba)
                        b.set_visible(visible)

            if marker is not 'none':
                line.set_marker(marker)
                line.set_markersize(markersize)
                line.set_markerfacecolor(markerfacecolor)
                line.set_markeredgecolor(markeredgecolor)

        # Set / Images
        for index, image_settings in enumerate(images):
            image = imagedict[imagelabels[index]]
            label, cmap, low, high, interpolation = image_settings
            image.set_label(label)
            image.set_cmap(cm.get_cmap(cmap))
            image.set_clim(*sorted([low, high]))
            image.set_interpolation(interpolation)

        # re-generate legend, if checkbox is checked
        if generate_legend:
            outils.regenerate_legend(axes)

        # Redraw
        figure = axes.get_figure()
        figure.canvas.draw()
        if not (axes.get_xlim() == orig_xlim and axes.get_ylim() == orig_ylim):
            figure.canvas.toolbar.push_current()

    data = formlayout.fedit(datalist, title="Figure options", parent=parent,
                            icon=get_icon('qt4_editor_options.svg'),
                            apply=apply_callback)
    if data is not None:
        apply_callback(data)