Ejemplo n.º 1
1
class HydroprintGUI(myqt.DialogWindow):

    ConsoleSignal = QSignal(str)

    def __init__(self, datamanager, parent=None):
        super(HydroprintGUI, self).__init__(parent, maximize=True)

        self.__updateUI = True

        # Child widgets:

        self.dmngr = datamanager
        self.dmngr.wldsetChanged.connect(self.wldset_changed)
        self.dmngr.wxdsetChanged.connect(self.wxdset_changed)

        self.page_setup_win = PageSetupWin(self)
        self.page_setup_win.newPageSetupSent.connect(self.layout_changed)

        self.color_palette_win = ColorsSetupWin(self)
        self.color_palette_win.newColorSetupSent.connect(self.update_colors)

        # Memory path variable:

        self.save_fig_dir = self.workdir

        # Generate UI:

        self.__initUI__()

    def __initUI__(self):

        # ---- Toolbar

        self.btn_save = btn_save = QToolButtonNormal(icons.get_icon('save'))
        btn_save.setToolTip('Save the well hydrograph')

        # btn_draw is usefull for debugging purposes
        btn_draw = QToolButtonNormal(icons.get_icon('refresh'))
        btn_draw.setToolTip('Force a refresh of the well hydrograph')
        btn_draw.hide()

        self.btn_load_layout = QToolButtonNormal(
                icons.get_icon('load_graph_config'))
        self.btn_load_layout.setToolTip(
                "<p>Load graph layout for the current water level "
                " datafile if it exists</p>")
        self.btn_load_layout.clicked.connect(self.load_layout_isClicked)

        self.btn_save_layout = QToolButtonNormal(
                icons.get_icon('save_graph_config'))
        self.btn_save_layout.setToolTip('Save current graph layout')
        self.btn_save_layout.clicked.connect(self.save_layout_isClicked)

        btn_bestfit_waterlvl = QToolButtonNormal(icons.get_icon('fit_y'))
        btn_bestfit_waterlvl.setToolTip('Best fit the water level scale')

        btn_bestfit_time = QToolButtonNormal(icons.get_icon('fit_x'))
        btn_bestfit_time.setToolTip('Best fit the time scale')

        self.btn_page_setup = QToolButtonNormal(icons.get_icon('page_setup'))
        self.btn_page_setup.setToolTip('Show the page setup window')
        self.btn_page_setup.clicked.connect(self.page_setup_win.show)

        btn_color_pick = QToolButtonNormal(icons.get_icon('color_picker'))
        btn_color_pick.setToolTip('<p>Show a window to setup the color palette'
                                  ' used to draw the hydrograph</p.')
        btn_color_pick.clicked.connect(self.color_palette_win.show)

        self.btn_language = LangToolButton()
        self.btn_language.setToolTip(
            "Set the language of the text shown in the graph.")
        self.btn_language.sig_lang_changed.connect(self.layout_changed)
        self.btn_language.setIconSize(icons.get_iconsize('normal'))

        # ---- Zoom Panel

        btn_zoom_out = QToolButtonSmall(icons.get_icon('zoom_out'))
        btn_zoom_out.setToolTip('Zoom out (ctrl + mouse-wheel-down)')
        btn_zoom_out.clicked.connect(self.zoom_out)

        btn_zoom_in = QToolButtonSmall(icons.get_icon('zoom_in'))
        btn_zoom_in.setToolTip('Zoom in (ctrl + mouse-wheel-up)')
        btn_zoom_in.clicked.connect(self.zoom_in)

        self.zoom_disp = QSpinBox()
        self.zoom_disp.setAlignment(Qt.AlignCenter)
        self.zoom_disp.setButtonSymbols(QAbstractSpinBox.NoButtons)
        self.zoom_disp.setReadOnly(True)
        self.zoom_disp.setSuffix(' %')
        self.zoom_disp.setRange(0, 9999)
        self.zoom_disp.setValue(100)

        zoom_pan = myqt.QFrameLayout()
        zoom_pan.setSpacing(3)
        zoom_pan.addWidget(btn_zoom_out, 0, 0)
        zoom_pan.addWidget(btn_zoom_in, 0, 1)
        zoom_pan.addWidget(self.zoom_disp, 0, 2)

        # LAYOUT :

        btn_list = [btn_save, btn_draw,
                    self.btn_load_layout, self.btn_save_layout, VSep(),
                    btn_bestfit_waterlvl, btn_bestfit_time, VSep(),
                    self.btn_page_setup, btn_color_pick, self.btn_language,
                    VSep(), zoom_pan]

        subgrid_toolbar = QGridLayout()
        toolbar_widget = QWidget()

        row = 0
        for col, btn in enumerate(btn_list):
            subgrid_toolbar.addWidget(btn, row, col)

        subgrid_toolbar.setSpacing(5)
        subgrid_toolbar.setContentsMargins(0, 0, 0, 0)
        subgrid_toolbar.setColumnStretch(col + 1, 100)

        toolbar_widget.setLayout(subgrid_toolbar)

        # ---- LEFT PANEL

        # SubGrid Hydrograph Frame :

        self.hydrograph = hydrograph.Hydrograph()
        self.hydrograph_scrollarea = mplFigViewer.ImageViewer()
        self.hydrograph_scrollarea.zoomChanged.connect(self.zoom_disp.setValue)

        grid_hydrograph = QGridLayout()
        grid_hydrograph.addWidget(self.hydrograph_scrollarea, 0, 0)
        grid_hydrograph.setRowStretch(0, 500)
        grid_hydrograph.setColumnStretch(0, 500)
        grid_hydrograph.setContentsMargins(0, 0, 0, 0)  # (L, T, R, B)

        # ASSEMBLING SubGrids :

        grid_layout = QGridLayout()
        self.grid_layout_widget = QFrame()

        row = 0
        grid_layout.addWidget(toolbar_widget, row, 0)
        row += 1
        grid_layout.addLayout(grid_hydrograph, row, 0)

        grid_layout.setContentsMargins(0, 0, 0, 0)  # (L, T, R, B)
        grid_layout.setSpacing(5)
        grid_layout.setColumnStretch(0, 500)
        grid_layout.setRowStretch(1, 500)

        self.grid_layout_widget.setLayout(grid_layout)

        # ---- Right Panel

        self.tabscales = self.__init_scalesTabWidget__()

        self.right_panel = myqt.QFrameLayout()
        self.right_panel.addWidget(self.dmngr, 0, 0)
        self.right_panel.addWidget(self.tabscales, 1, 0)
        self.right_panel.setRowStretch(2, 100)

        self.right_panel.setSpacing(15)

        # ---- MAIN GRID

        mainGrid = QGridLayout()

        mainGrid.addWidget(self.grid_layout_widget, 0, 0)
        mainGrid.addWidget(VSep(), 0, 1)
        mainGrid.addWidget(self.right_panel, 0, 2)

        mainGrid.setContentsMargins(10, 10, 10, 10)  # (L, T, R, B)
        mainGrid.setSpacing(15)
        mainGrid.setColumnStretch(0, 500)
        mainGrid.setColumnMinimumWidth(2, 250)

        self.setLayout(mainGrid)

        # ---- EVENTS

        # Toolbox Layout :

        btn_bestfit_waterlvl.clicked.connect(self.best_fit_waterlvl)
        btn_bestfit_time.clicked.connect(self.best_fit_time)
        btn_draw.clicked.connect(self.draw_hydrograph)
        btn_save.clicked.connect(self.select_save_path)

        # Hydrograph Layout :

        self.Ptot_scale.valueChanged.connect(self.layout_changed)
        self.qweather_bin.currentIndexChanged.connect(self.layout_changed)

        # ---- Init Image

        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)

    def __init_scalesTabWidget__(self):

        class QRowLayout(QGridLayout):
            def __init__(self, items, parent=None):
                super(QRowLayout, self).__init__(parent)

                for col, item in enumerate(items):
                    self.addWidget(item, 0, col)

                self.setContentsMargins(0, 0, 0, 0)
                self.setColumnStretch(0, 100)

        # ---- Time axis properties

        # Generate the widgets :

        self.date_start_widget = QDateEdit()
        self.date_start_widget.setDisplayFormat('01 / MM / yyyy')
        self.date_start_widget.setAlignment(Qt.AlignCenter)
        self.date_start_widget.dateChanged.connect(self.layout_changed)

        self.date_end_widget = QDateEdit()
        self.date_end_widget.setDisplayFormat('01 / MM / yyyy')
        self.date_end_widget.setAlignment(Qt.AlignCenter)
        self.date_end_widget.dateChanged.connect(self.layout_changed)

        self.time_scale_label = QComboBox()
        self.time_scale_label.setEditable(False)
        self.time_scale_label.setInsertPolicy(QComboBox.NoInsert)
        self.time_scale_label.addItems(['Month', 'Year'])
        self.time_scale_label.setCurrentIndex(0)
        self.time_scale_label.currentIndexChanged.connect(self.layout_changed)

        self.dateDispFreq_spinBox = QSpinBox()
        self.dateDispFreq_spinBox.setSingleStep(1)
        self.dateDispFreq_spinBox.setMinimum(1)
        self.dateDispFreq_spinBox.setMaximum(100)
        self.dateDispFreq_spinBox.setValue(
            self.hydrograph.date_labels_pattern)
        self.dateDispFreq_spinBox.setAlignment(Qt.AlignCenter)
        self.dateDispFreq_spinBox.setKeyboardTracking(False)
        self.dateDispFreq_spinBox.valueChanged.connect(self.layout_changed)

        # Setting up the layout :

        widget_time_scale = QFrame()
        widget_time_scale.setFrameStyle(0)
        grid_time_scale = QGridLayout()

        GRID = [[QLabel('From :'), self.date_start_widget],
                [QLabel('To :'), self.date_end_widget],
                [QLabel('Scale :'), self.time_scale_label],
                [QLabel('Date Disp. Pattern:'),
                 self.dateDispFreq_spinBox]]

        for i, ROW in enumerate(GRID):
            grid_time_scale.addLayout(QRowLayout(ROW), i, 1)

        grid_time_scale.setVerticalSpacing(5)
        grid_time_scale.setContentsMargins(10, 10, 10, 10)

        widget_time_scale.setLayout(grid_time_scale)

        # ----- Water level axis properties

        # Widget :

        self.waterlvl_scale = QDoubleSpinBox()
        self.waterlvl_scale.setSingleStep(0.05)
        self.waterlvl_scale.setMinimum(0.05)
        self.waterlvl_scale.setSuffix('  m')
        self.waterlvl_scale.setAlignment(Qt.AlignCenter)
        self.waterlvl_scale.setKeyboardTracking(False)
        self.waterlvl_scale.valueChanged.connect(self.layout_changed)
        self.waterlvl_scale.setFixedWidth(100)

        self.waterlvl_max = QDoubleSpinBox()
        self.waterlvl_max.setSingleStep(0.1)
        self.waterlvl_max.setSuffix('  m')
        self.waterlvl_max.setAlignment(Qt.AlignCenter)
        self.waterlvl_max.setMinimum(-1000)
        self.waterlvl_max.setMaximum(1000)
        self.waterlvl_max.setKeyboardTracking(False)
        self.waterlvl_max.valueChanged.connect(self.layout_changed)
        self.waterlvl_max.setFixedWidth(100)

        self.NZGridWL_spinBox = QSpinBox()
        self.NZGridWL_spinBox.setSingleStep(1)
        self.NZGridWL_spinBox.setMinimum(1)
        self.NZGridWL_spinBox.setMaximum(50)
        self.NZGridWL_spinBox.setValue(self.hydrograph.NZGrid)
        self.NZGridWL_spinBox.setAlignment(Qt.AlignCenter)
        self.NZGridWL_spinBox.setKeyboardTracking(False)
        self.NZGridWL_spinBox.valueChanged.connect(self.layout_changed)
        self.NZGridWL_spinBox.setFixedWidth(100)

        self.datum_widget = QComboBox()
        self.datum_widget.addItems(['Ground Surface', 'Sea Level'])
        self.datum_widget.currentIndexChanged.connect(self.layout_changed)

        # Layout :

        subgrid_WLScale = QGridLayout()

        GRID = [[QLabel('Minimum :'), self.waterlvl_max],
                [QLabel('Scale :'), self.waterlvl_scale],
                [QLabel('Grid Divisions :'), self.NZGridWL_spinBox],
                [QLabel('Datum :'), self.datum_widget]]

        for i, ROW in enumerate(GRID):
            subgrid_WLScale.addLayout(QRowLayout(ROW), i, 1)

        subgrid_WLScale.setVerticalSpacing(5)
        subgrid_WLScale.setContentsMargins(10, 10, 10, 10)  # (L, T, R, B)

        WLScale_widget = QFrame()
        WLScale_widget.setFrameStyle(0)
        WLScale_widget.setLayout(subgrid_WLScale)

        # ---- Weather Axis

        # Widgets :

        self.Ptot_scale = QSpinBox()
        self.Ptot_scale.setSingleStep(5)
        self.Ptot_scale.setMinimum(5)
        self.Ptot_scale.setMaximum(500)
        self.Ptot_scale.setValue(20)
        self.Ptot_scale.setSuffix('  mm')
        self.Ptot_scale.setAlignment(Qt.AlignCenter)

        self.qweather_bin = QComboBox()
        self.qweather_bin.setEditable(False)
        self.qweather_bin.setInsertPolicy(QComboBox.NoInsert)
        self.qweather_bin.addItems(['day', 'week', 'month'])
        self.qweather_bin.setCurrentIndex(1)

        # Layout :

        layout = QGridLayout()

        GRID = [[QLabel('Precip. Scale :'), self.Ptot_scale],
                [QLabel('Resampling :'), self.qweather_bin]]

        for i, row in enumerate(GRID):
            layout.addLayout(QRowLayout(row), i, 1)

        layout.setVerticalSpacing(5)
        layout.setContentsMargins(10, 10, 10, 10)  # (L,T,R,B)
        layout.setRowStretch(i+1, 100)

        widget_weather_scale = QFrame()
        widget_weather_scale.setFrameStyle(0)
        widget_weather_scale.setLayout(layout)

        # ---- ASSEMBLING TABS

        tabscales = QTabWidget()
        tabscales.addTab(widget_time_scale, 'Time')
        tabscales.addTab(WLScale_widget, 'Water Level')
        tabscales.addTab(widget_weather_scale, 'Weather')

        return tabscales

    @property
    def workdir(self):
        return self.dmngr.workdir

    # ---- Utilities

    def zoom_in(self):
        self.hydrograph_scrollarea.zoomIn()

    def zoom_out(self):
        self.hydrograph_scrollarea.zoomOut()

    def update_colors(self):
        self.hydrograph.update_colors()
        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)

    # ---- Datasets Handlers

    @property
    def wldset(self):
        return self.dmngr.get_current_wldset()

    @property
    def wxdset(self):
        return self.dmngr.get_current_wxdset()

    def wldset_changed(self):
        """Handle when the water level dataset of the datamanager changes."""
        if self.wldset is None:
            self.clear_hydrograph()
            return
        else:
            self.hydrograph.set_wldset(self.wldset)
            self.hydrograph.gluedf = self.wldset.get_glue_at(-1)

        # Load the manual measurements.

        fname = os.path.join(
            self.workdir, "Water Levels", 'waterlvl_manual_measurements')
        tmeas, wlmeas = load_waterlvl_measures(fname, self.wldset['Well'])
        self.wldset.set_wlmeas(tmeas, wlmeas)

        # Setup the layout of the hydrograph.

        layout = self.wldset.get_layout()
        if layout is not None:
            msg = ("Loading existing graph layout for well %s." %
                   self.wldset['Well'])
            print(msg)
            self.ConsoleSignal.emit('<font color=black>%s</font>' % msg)
            self.load_graph_layout(layout)
        else:
            print('No graph layout exists for well %s.' % self.wldset['Well'])
            # Fit Water Level in Layout :
            self.__updateUI = False
            self.best_fit_waterlvl()
            self.best_fit_time()
            if self.dmngr.set_closest_wxdset() is None:
                self.draw_hydrograph()
            self.__updateUI = True

    def wxdset_changed(self):
        """Handle when the weather dataset of the datamanager changes."""
        if self.wldset is None:
            self.clear_hydrograph()
        else:
            self.hydrograph.set_wxdset(self.wxdset)
            QCoreApplication.processEvents()
            self.draw_hydrograph()

    # ---- Draw Hydrograph Handlers
    def best_fit_waterlvl(self):
        wldset = self.dmngr.get_current_wldset()
        if wldset is not None:
            WLscale, WLmin = self.hydrograph.best_fit_waterlvl()
            self.waterlvl_scale.setValue(WLscale)
            self.waterlvl_max.setValue(WLmin)

    def best_fit_time(self):
        wldset = self.dmngr.get_current_wldset()
        if wldset is not None:
            date0, date1 = self.hydrograph.best_fit_time(wldset.xldates)
            self.date_start_widget.setDate(QDate(date0[0], date0[1], date0[2]))
            self.date_end_widget.setDate(QDate(date1[0], date1[1], date1[2]))

    @QSlot()
    def mrc_wl_changed(self):
        """
        Force a redraw of the MRC water levels after the results have
        changed for the dataset.
        """
        self.hydrograph.draw_mrc_wl()
        self.hydrograph.setup_legend()
        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)

    @QSlot(GLUEDataFrameBase)
    def glue_wl_changed(self, gluedf):
        """
        Force a redraw of the GLUE water levels after the results have
        changed for the dataset.
        """
        self.hydrograph.set_gluedf(gluedf)
        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)

    def layout_changed(self):
        """
        When an element of the graph layout is changed in the UI.
        """

        if self.__updateUI is False:
            return

        self.update_graph_layout_parameter()

        if self.hydrograph.isHydrographExists is False:
            return

        sender = self.sender()

        if sender == self.btn_language:
            self.hydrograph.draw_ylabels()
            self.hydrograph.setup_xticklabels()
            self.hydrograph.setup_legend()
        elif sender in [self.waterlvl_max, self.waterlvl_scale]:
            self.hydrograph.setup_waterlvl_scale()
            self.hydrograph.draw_ylabels()
        elif sender == self.NZGridWL_spinBox:
            self.hydrograph.setup_waterlvl_scale()
            self.hydrograph.update_precip_scale()
            self.hydrograph.draw_ylabels()
        elif sender == self.Ptot_scale:
            self.hydrograph.update_precip_scale()
            self.hydrograph.draw_ylabels()
        elif sender == self.datum_widget:
            yoffset = int(self.wldset['Elevation']/self.hydrograph.WLscale)
            yoffset *= self.hydrograph.WLscale

            self.hydrograph.WLmin = (yoffset - self.hydrograph.WLmin)

            self.waterlvl_max.blockSignals(True)
            self.waterlvl_max.setValue(self.hydrograph.WLmin)
            self.waterlvl_max.blockSignals(False)

            # This is calculated so that trailing zeros in the altitude of the
            # well is not carried to the y axis labels, so that they remain a
            # int multiple of *WLscale*.

            self.hydrograph.setup_waterlvl_scale()
            self.hydrograph.draw_waterlvl()
            self.hydrograph.draw_ylabels()
        elif sender in [self.date_start_widget, self.date_end_widget]:
            self.hydrograph.set_time_scale()
            self.hydrograph.draw_weather()
            self.hydrograph.draw_figure_title()
        elif sender == self.dateDispFreq_spinBox:
            self.hydrograph.set_time_scale()
            self.hydrograph.setup_xticklabels()
        elif sender == self.page_setup_win:
            self.hydrograph.update_fig_size()
            # Implicitly call : set_margins()
            #                   draw_ylabels()
            #                   set_time_scale()
            #                   draw_figure_title
            self.hydrograph.draw_waterlvl()
            self.hydrograph.setup_legend()
        elif sender == self.qweather_bin:
            self.hydrograph.resample_bin()
            self.hydrograph.draw_weather()
            self.hydrograph.draw_ylabels()
        elif sender == self.time_scale_label:
            self.hydrograph.set_time_scale()
            self.hydrograph.draw_weather()
        else:
            print('No action for this widget yet.')

        # !!!! temporary fix until I can find a better solution !!!!

#        sender.blockSignals(True)
        if type(sender) in [QDoubleSpinBox, QSpinBox]:
            sender.setReadOnly(True)

        for i in range(10):
            QCoreApplication.processEvents()
        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)
        for i in range(10):
            QCoreApplication.processEvents()

        if type(sender) in [QDoubleSpinBox, QSpinBox]:
            sender.setReadOnly(False)
#        sender.blockSignals(False)

    def update_graph_layout_parameter(self):

        # language :

        self.hydrograph.language = self.btn_language.language

        # Scales :

        self.hydrograph.WLmin = self.waterlvl_max.value()
        self.hydrograph.WLscale = self.waterlvl_scale.value()
        self.hydrograph.RAINscale = self.Ptot_scale.value()
        self.hydrograph.NZGrid = self.NZGridWL_spinBox.value()

        # WL Datum :

        self.hydrograph.WLdatum = self.datum_widget.currentIndex()

        # Dates :

        self.hydrograph.datemode = self.time_scale_label.currentText()

        year = self.date_start_widget.date().year()
        month = self.date_start_widget.date().month()
        self.hydrograph.TIMEmin = xldate_from_date_tuple((year, month, 1), 0)

        year = self.date_end_widget.date().year()
        month = self.date_end_widget.date().month()
        self.hydrograph.TIMEmax = xldate_from_date_tuple((year, month, 1), 0)

        self.hydrograph.date_labels_pattern = self.dateDispFreq_spinBox.value()

        # Page Setup :

        self.hydrograph.fwidth = self.page_setup_win.pageSize[0]
        self.hydrograph.fheight = self.page_setup_win.pageSize[1]
        self.hydrograph.va_ratio = self.page_setup_win.va_ratio

        self.hydrograph.trend_line = self.page_setup_win.isTrendLine
        self.hydrograph.isLegend = self.page_setup_win.isLegend
        self.hydrograph.isGraphTitle = self.page_setup_win.isGraphTitle
        self.hydrograph.set_meteo_on(self.page_setup_win.is_meteo_on)
        self.hydrograph.set_glue_wl_on(self.page_setup_win.is_glue_wl_on)
        self.hydrograph.set_mrc_wl_on(self.page_setup_win.is_mrc_wl_on)
        self.hydrograph.set_figframe_lw(self.page_setup_win.figframe_lw)

        # Weather bins :

        self.hydrograph.bwidth_indx = self.qweather_bin.currentIndex()

    def clear_hydrograph(self):
        """Clear the hydrograph figure to show only a blank canvas."""
        self.hydrograph.clf()
        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)

    def draw_hydrograph(self):
        if self.dmngr.wldataset_count() == 0:
            msg = 'Please import a valid water level data file first.'
            self.ConsoleSignal.emit('<font color=red>%s</font>' % msg)
            self.emit_warning(msg)
            return

        self.update_graph_layout_parameter()

        # Generate and Display Graph :

        for i in range(5):
            QCoreApplication.processEvents()

        QApplication.setOverrideCursor(Qt.WaitCursor)

        self.hydrograph.set_wldset(self.dmngr.get_current_wldset())
        self.hydrograph.set_wxdset(self.dmngr.get_current_wxdset())
        self.hydrograph.generate_hydrograph()

        self.hydrograph_scrollarea.load_mpl_figure(self.hydrograph)

        QApplication.restoreOverrideCursor()

    def select_save_path(self):
        """
        Open a dialog where the user can select a file name to save the
        hydrograph.
        """
        if self.wldset is None:
            return

        ffmat = "*.pdf;;*.svg;;*.png"
        fname = find_unique_filename(osp.join(
            self.save_fig_dir, 'hydrograph_%s.pdf' % self.wldset['Well']))

        fname, ftype = QFileDialog.getSaveFileName(
            self, "Save Figure", fname, ffmat)
        if fname:
            ftype = ftype.replace('*', '')
            fname = fname if fname.endswith(ftype) else fname + ftype
            self.save_fig_dir = os.path.dirname(fname)

            try:
                self.save_figure(fname)
            except PermissionError:
                msg = "The file is in use by another application or user."
                QMessageBox.warning(self, 'Warning', msg, QMessageBox.Ok)
                self.select_save_path()

    def save_figure(self, fname):
        """Save the hydrograph figure in a file."""
        self.hydrograph.generate_hydrograph()
        self.hydrograph.savefig(fname)

    # ---- Graph Layout Handlers

    def load_layout_isClicked(self):
        """Handle when the button to load the graph layout is clicked."""
        if self.wldset is None:
            self.emit_warning(
                "Please import a valid water level data file first.")
            return

        layout = self.wldset.get_layout()
        if layout is None:
            self.emit_warning(
                "No graph layout exists for well %s." % self.wldset['Well'])
        else:
            self.load_graph_layout(layout)

    def load_graph_layout(self, layout):
        """Load the graph layout into the GUI."""

        self.__updateUI = False

        # Scales :

        date = layout['TIMEmin']
        date = xldate_as_tuple(date, 0)
        self.date_start_widget.setDate(QDate(date[0], date[1], date[2]))

        date = layout['TIMEmax']
        date = xldate_as_tuple(date, 0)
        self.date_end_widget.setDate(QDate(date[0], date[1], date[2]))

        self.dateDispFreq_spinBox.setValue(layout['date_labels_pattern'])

        self.waterlvl_scale.setValue(layout['WLscale'])
        self.waterlvl_max.setValue(layout['WLmin'])
        self.NZGridWL_spinBox.setValue(layout['NZGrid'])
        self.Ptot_scale.setValue(layout['RAINscale'])

        x = ['mbgs', 'masl'].index(layout['WLdatum'])
        self.datum_widget.setCurrentIndex(x)

        self.qweather_bin.setCurrentIndex(layout['bwidth_indx'])
        self.time_scale_label.setCurrentIndex(
            self.time_scale_label.findText(layout['datemode']))

        # ---- Language and colors
        self.btn_language.set_language(layout['language'])
        self.color_palette_win.load_colors()

        # ---- Page Setup

        self.page_setup_win.pageSize = (layout['fwidth'], layout['fheight'])
        self.page_setup_win.va_ratio = layout['va_ratio']
        self.page_setup_win.isLegend = layout['legend_on']
        self.page_setup_win.isGraphTitle = layout['title_on']
        self.page_setup_win.isTrendLine = layout['trend_line']
        self.page_setup_win.is_meteo_on = layout['meteo_on']
        self.page_setup_win.is_glue_wl_on = layout['glue_wl_on']
        self.page_setup_win.is_mrc_wl_on = layout['mrc_wl_on']
        self.page_setup_win.figframe_lw = layout['figframe_lw']

        self.page_setup_win.legend_on.set_value(layout['legend_on'])
        self.page_setup_win.title_on.set_value(layout['title_on'])
        self.page_setup_win.wltrend_on.set_value(layout['trend_line'])
        self.page_setup_win.meteo_on.set_value(layout['meteo_on'])
        self.page_setup_win.glue_wl_on.set_value(layout['glue_wl_on'])
        self.page_setup_win.mrc_wl_on.set_value(layout['mrc_wl_on'])
        self.page_setup_win.fframe_lw_widg.setValue(layout['figframe_lw'])

        self.page_setup_win.fwidth.setValue(layout['fwidth'])
        self.page_setup_win.fheight.setValue(layout['fheight'])
        self.page_setup_win.va_ratio_spinBox.setValue(layout['va_ratio'])

        # Check if Weather Dataset :

        if layout['wxdset'] in self.dmngr.wxdsets:
            self.dmngr.set_current_wxdset(layout['wxdset'])
        else:
            if self.dmngr.set_closest_wxdset() is None:
                self.draw_hydrograph()
        self.__updateUI = True

    def save_layout_isClicked(self):
        wldset = self.wldset
        if wldset is None:
            self.emit_warning(
                "Please import a valid water level data file first.")
            return

        layout = wldset.get_layout()
        if layout is not None:
            msg = ('A graph layout already exists for well %s.Do you want to'
                   ' you want to replace it?') % wldset['Well']
            reply = QMessageBox.question(self, 'Save Graph Layout', msg,
                                         QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                self.save_graph_layout()
            elif reply == QMessageBox.No:
                msg = "Graph layout not saved for well %s." % wldset['Well']
                self.ConsoleSignal.emit('<font color=black>%s' % msg)
        else:
            self.save_graph_layout()

    def save_graph_layout(self):
        """Save the graph layout in the project hdf5 file."""
        print("Saving the graph layout for well %s..." % self.wldset['Well'],
              end=" ")

        layout = {'WLmin': self.waterlvl_max.value(),
                  'WLscale': self.waterlvl_scale.value(),
                  'RAINscale': self.Ptot_scale.value(),
                  'fwidth': self.page_setup_win.pageSize[0],
                  'fheight': self.page_setup_win.pageSize[1],
                  'va_ratio': self.page_setup_win.va_ratio,
                  'NZGrid': self.NZGridWL_spinBox.value(),
                  'bwidth_indx': self.qweather_bin.currentIndex(),
                  'date_labels_pattern': self.dateDispFreq_spinBox.value(),
                  'datemode': self.time_scale_label.currentText()}
        layout['wxdset'] = None if self.wxdset is None else self.wxdset.name

        year = self.date_start_widget.date().year()
        month = self.date_start_widget.date().month()
        layout['TIMEmin'] = xldate_from_date_tuple((year, month, 1), 0)

        year = self.date_end_widget.date().year()
        month = self.date_end_widget.date().month()
        layout['TIMEmax'] = xldate_from_date_tuple((year, month, 1), 0)

        if self.datum_widget.currentIndex() == 0:
            layout['WLdatum'] = 'mbgs'
        else:
            layout['WLdatum'] = 'masl'

        # ---- Page Setup

        layout['title_on'] = bool(self.page_setup_win.isGraphTitle)
        layout['legend_on'] = bool(self.page_setup_win.isLegend)
        layout['language'] = self.btn_language.language
        layout['trend_line'] = bool(self.page_setup_win.isTrendLine)
        layout['meteo_on'] = bool(self.page_setup_win.is_meteo_on)
        layout['glue_wl_on'] = bool(self.page_setup_win.is_glue_wl_on)
        layout['mrc_wl_on'] = bool(self.page_setup_win.is_mrc_wl_on)
        layout['figframe_lw'] = self.page_setup_win.figframe_lw

        # Save the colors :

        cdb = ColorsReader()
        cdb.load_colors_db()
        layout['colors'] = cdb.RGB

        # Save the layout :

        self.wldset.save_layout(layout)
        msg = 'Layout saved successfully for well %s.' % self.wldset['Well']
        self.ConsoleSignal.emit('<font color=black>%s</font>' % msg)
        print("done")
Ejemplo n.º 2
0
    def InitUI(self):

        self.form = QFormLayout(self)

        self.nama = QLineEdit(self)
        self.nama.setPlaceholderText("Nama Dokter")
        self.form.addRow("Nama Dokter", self.nama)

        self.Jdwl = QDateEdit(self)
        self.Jdwl.setCalendarPopup(True)
        self.form.addRow("Jadwal Dokter", self.Jdwl)

        self.Id = QLineEdit(self)
        self.Id.setValidator(QIntValidator())
        self.Id.setMaxLength(16)
        self.form.addRow("ID DOKTER", self.Id)

        self.noSeri = QLineEdit(self)
        self.noSeri.setInputMask("9999")
        self.form.addRow("No Serial Dokter", self.noSeri)

        self.Spesialis = QComboBox()
        self.Spesialis.addItem("RME")
        self.Spesialis.addItem("RKE")
        self.Spesialis.addRow("Spesialis ",self.Spesialis)

        self.submit = QPushButton(self)
        self.submit.setText("Update")
        self.submit.clicked.connect(self.update_btn)

        self.clear = QPushButton(self)
        self.clear.setText("Bersihkan")
        self.clear.clicked.connect(self.clear_btn)

        self.form.addRow(self.clear,self.submit)
Ejemplo n.º 3
0
    def __init__(self, parent, iBacklogData):
        super().__init__(parent)

        self.backlogData = iBacklogData

        self.setWindowTitle("Duty details")
        self.setMinimumWidth(500)

        mainLayout = QVBoxLayout(self)

        self.currDutyDate = self.backlogData.currDuty.date
        currDutyDateLabel = QLabel("Workday date: ")
        self.currDutyDateEdit = QDateEdit(self)

        self.currDutyDateLayout = QHBoxLayout(self)
        self.currDutyDateLayout.addWidget(currDutyDateLabel)
        self.currDutyDateLayout.addWidget(self.currDutyDateEdit)

        self.initCurrDutyDateEdit()

        self.dutySummaryTableWidget = QTableWidget(self)

        summaryDailyTasksLabel = QLabel("Summary of daily tasks")
        self.initDutySummaryTableWidget()

        self.totalCompTime = datetime.timedelta(
            seconds=self.backlogData.currDuty.totalTimeCompleted)
        self.totalCompTimeLabel = QLabel("Total completed time: " +
                                         str(self.totalCompTime))

        mainLayout.addLayout(self.currDutyDateLayout)
        mainLayout.addWidget(summaryDailyTasksLabel)
        mainLayout.addWidget(self.dutySummaryTableWidget)
        mainLayout.addWidget(self.totalCompTimeLabel)
Ejemplo n.º 4
0
    def _initUI(self):
        self._name = QLineEdit()
        self._name.setFixedHeight(30)
        self._name.setPlaceholderText("produto")

        self._stock = QSpinBox()
        self._stock.setMaximum(100000)
        self._stock.setFixedHeight(30)
        self._stock.setValue(10)

        self._price = QDoubleSpinBox()
        self._price.setDecimals(2)
        self._price.setMaximum(99999.99)
        self._price.setFixedHeight(30)
        self._price.setValue(10.0)

        self.inputCategory = QComboBox()
        self.inputCategory.setFixedHeight(30)

        self._date = QDateEdit()
        self._date.setDate(QDate.currentDate())

        self.addField("Nome do Produto", self._name)
        self.addField("Preço(R$)", self._price)
        self.addField("Estoque(Unidade)", self._stock)
        self.addField("Categoria", self.inputCategory)
        #self.addField("Validade", self._date)
        super(ProductWindow, self)._initUI()
Ejemplo n.º 5
0
class DateCtrl(BaseParamWidget):
    def __init__(self, layout_dir: str, title, initial_date):
        super().__init__(layout_dir)
        self.prefix = lab_title = QLabel(text=title)
        path_layout = QHBoxLayout()
        path_layout.addWidget(lab_title)

        self.ctrl = QDateEdit()
        path_layout.addWidget(self.ctrl)

        calendar_widget = QCalendar()
        self.ctrl.setCalendar(calendar_widget)

        self.central_layout.addLayout(path_layout)
        self.set_value(initial_date)

    def set_value(self, value: Union[Tuple[int, int, int], float, int]):
        if isinstance(value, tuple):
            assert len(value) == 3
            date = QDate(*value)
        elif isinstance(value, (float, int)):
            loc_time = time.localtime(value)
            print(loc_time)
            date = QDate(loc_time.tm_year, loc_time.tm_mon, loc_time.tm_mday)
        else:
            raise ValueError("value is not allowed", value)
        self.ctrl.setDate(date)

    def get_value(self) -> float:
        """
        计算值
        :return:
        """
        return time.mktime(self.ctrl.date().toPyDate().timetuple())
Ejemplo n.º 6
0
 def setWidgets(self):
     '''Cria os Widgets da tela da área do gerente'''
     self.conteudo = QWidget()
     self.lbl_title = QLabel("DADOS DO PRODUTO")
     self.lbl_title.setStyleSheet("QLabel{font:bold}")
     self.edit_codigo = QLineEdit()
     self.edit_codigo.setValidator(QRegExpValidator(
         QRegExp("[0-9]{1,99}"
                 )))  #Valida Numeros inteiros no min 1 digito e no max 99
     self.edit_lote = QLineEdit()
     #Cria o selectbox e insere os valores do banco de dados no mesmo
     self.cb_categoria = QComboBox()
     for id_categoria, categoria in self.categorias:
         self.cb_categoria.addItem(categoria, id_categoria)
     self.edit_nome = QLineEdit()
     self.edit_descricao = QLineEdit()
     self.edit_quantidade = QLineEdit()
     self.edit_quantidade.setValidator(
         QRegExpValidator(QRegExp("\-?\d+\.\d+")))
     self.cb_unidade = QComboBox()
     #Cria o selectbox e insere os valores do banco de dados no mesmo
     for id_unidade, sigla, unidade in self.unidades:
         self.cb_unidade.addItem(unidade, id_unidade)
     self.edit_peso = QLineEdit()
     self.edit_peso.setValidator(QRegExpValidator(QRegExp("\-?\d+\.\d+")))
     self.edit_local = QLineEdit()
     self.edit_data = QDateEdit(QDate.currentDate())
     self.edit_data.setDisplayFormat("yyyy/MM/dd")
     self.edit_data.setCalendarPopup(True)
     self.btn_cadastrar = QPushButton("Cadastrar")
     self.btn_cadastrar.setAutoDefault(True)
Ejemplo n.º 7
0
    def initUI(self):
        lbl = QLabel('QDateEdit')

        self.dateEditWidget = QDateEdit()
        # theDate = QDate()
        # self.dateEditWidget.setDate(theDate.currentDate())    # 현재 날짜
        # theDate.setDate()
        # self.dateEditWidget.setDate(QDate.currentDate())    # 현재 날짜
        self.dateEditWidget.setMinimumDate(QDate(2000, 1, 1))
        self.dateEditWidget.setMaximumDate(QDate(2100, 12, 31))
        self.dateEditWidget.setDisplayFormat('yyyy.MM.dd')
        self.dateEditWidget.setCalendarPopup(True)
        self.dateEditWidget.setDate(QDate(2020, 5, 1))    # 지정한 날짜

        # self.dateEditWidget.setDate(QDate.currentDate())

        self.dateEditWidget.dateChanged.connect(self.__dateChanged)

        vbox = QVBoxLayout()
        vbox.addWidget(lbl)
        vbox.addWidget(self.dateEditWidget)
        vbox.addStretch()

        self.setLayout(vbox)

        self.setWindowTitle('QDateEdit')
        self.setGeometry(300, 300, 300, 200)
Ejemplo n.º 8
0
 def __init__(self, sms_data, *args, **kwargs):
     super(EditSMSLink, self).__init__(*args, **kwargs)
     layout = QVBoxLayout(margin=0)
     print(sms_data)
     self.sms_id = sms_data['id']
     # 时间布局
     date_time_layout = QHBoxLayout()
     self.date_edit = QDateEdit(QDate.fromString(sms_data['date'], 'yyyy-MM-dd'))
     self.date_edit.setCalendarPopup(True)
     self.date_edit.setDisplayFormat('yyyy-MM-dd')
     date_time_layout.addWidget(QLabel('日期:'))
     date_time_layout.addWidget(self.date_edit)
     date_time_layout.addWidget(QLabel('时间:'))
     self.time_edit = QTimeEdit(QTime.fromString(sms_data['time'], 'HH:mm:ss'))
     self.time_edit.setDisplayFormat('HH:mm:ss')
     date_time_layout.addWidget(self.time_edit)
     date_time_layout.addStretch()
     layout.addLayout(date_time_layout)
     self.show_tips = QLabel()
     self.text_edit = QTextEdit(textChanged=self.set_show_tips_null)
     self.text_edit.setPlainText(sms_data['content'])
     layout.addWidget(self.text_edit)
     layout.addWidget(self.show_tips)
     layout.addWidget(QPushButton('确定', clicked=self.commit_sms_edited), alignment=Qt.AlignRight)
     self.setLayout(layout)
     self.resize(420, 240)
     self.setWindowTitle('编辑短信通')
Ejemplo n.º 9
0
    def __init__(self):
        super().__init__()
        self.id_label = QLabel()
        self.id_label.setText('')
        self.order_no_box = QLineEdit(maximumWidth=40)
        self.date_box = QDateEdit(datetime.now().date())
        self.customer_box = QLineEdit(maximumWidth=300)
        self.project_box = QLineEdit(maximumWidth=300)
        self.total_box = QLineEdit(maximumWidth=100)

        self.cancel_button = QPushButton('Cancel')
        self.cancel_button.clicked.connect(lambda: self.reject())
        self.save_button = QPushButton('Save')
        self.save_button.clicked.connect(self.save_entry)

        entry_layout = QFormLayout()
        entry_layout.addRow('&Sale ID', self.id_label)
        entry_layout.addRow('&Order No.', self.order_no_box)
        entry_layout.addRow('&Date', self.date_box)
        entry_layout.addRow('&Customer', self.customer_box)
        entry_layout.addRow('&Project', self.project_box)
        entry_layout.addRow('&Sale Total', self.total_box)

        button_layout = QHBoxLayout()
        button_layout.addWidget(self.cancel_button)
        button_layout.addWidget(self.save_button)

        container_layout = QVBoxLayout()
        container_layout.addLayout(entry_layout)
        container_layout.addLayout(button_layout)

        self.setLayout(container_layout)
Ejemplo n.º 10
0
 def add_date_field(self,
                    f_title,
                    top,
                    left,
                    f_date,
                    widthchange=0,
                    need_calendar=True,
                    default_value=QDate(1980, 1, 1),
                    readonly=False,
                    label_margin=2,
                    label_font_size=LABEL_FONT_SIZE,
                    field_size=4):
     label = QLabel(self.parent)
     label.setText(f_title)
     font = QFont()
     font.setPointSize(label_font_size)
     label.setFont(font)
     geo_label = QRect(left * self.width_step, top,
                       label_margin * self.width_step, 30)
     label.setGeometry(geo_label)
     field = QDateEdit(self.parent)
     field.setCalendarPopup(need_calendar)
     geo_field = QRect((left + label_margin) * self.width_step, top,
                       field_size * self.width_step, 30)
     field.setGeometry(geo_field)
     if f_date:
         Defdate = QDate(int(f_date.split('.')[2]),
                         int(f_date.split('.')[1]),
                         int(f_date.split('.')[0]))
     else:
         Defdate = default_value
     field.setDate(Defdate)
     field.setReadOnly(readonly)
     return field
Ejemplo n.º 11
0
class AddNewsForm(QWidget):
    def __init__(self, url=0):
        super().__init__()
        self.initUI()
        self.setupPars(url)
        self.connectSlots()

    def initUI(self):
        vLay = QVBoxLayout()

        h1 = QHBoxLayout()
        self.lab1 = QLabel('Заголовок : ')
        self.leHeader = QLineEdit()
        h1.addWidget(self.lab1)
        h1.addWidget(self.leHeader)
        vLay.addLayout(h1)

        h2 = QHBoxLayout()
        self.lab2 = QLabel('URL : ')
        self.leURL = QLineEdit()
        h2.addWidget(self.lab2)
        h2.addWidget(self.leURL)
        vLay.addLayout(h2)

        h3 = QHBoxLayout()
        self.lab3 = QLabel('Дата : ')
        self.dateEdit = QDateEdit()
        h3.addWidget(self.lab3)
        h3.addWidget(self.dateEdit)
        self.dateEdit.setDate(QDate.currentDate())
        vLay.addLayout(h3)

        self.pbSave = QPushButton('Сохранить')

        vLay.addWidget(self.pbSave)

        self.setWindowTitle('Добавление новости')
        self.setLayout(vLay)

    def getPyDate(self):
        cur_date = self.dateEdit.date()
        return cur_date.toPyDate()

    def setupPars(self, url):
        if url:
            title = url[0]
            if '|' in title:
                title = title.split('|')[0]
            self.leURL.setText(title)
            self.leHeader.setText(url[1])
        self.webData = WebPageData()

    def connectSlots(self):
        self.pbSave.clicked.connect(self.saveRecord)

    def saveRecord(self):
        self.webData.insertRecord(title=self.leHeader.text(),
                                  url=self.leURL.text(),
                                  date=self.getPyDate())
        self.close()
Ejemplo n.º 12
0
    def inputBarang(self):
        self.form = QFormLayout(self)

        self.barang = QLineEdit(self)
        self.barang.setPlaceholderText("Nama Barang")
        self.form.addRow("Nama Barang", self.barang)

        self.lokasi = QLineEdit(self)
        self.lokasi.setPlaceholderText("Lokasi")
        self.form.addRow("Lokasi", self.lokasi)

        self.tglMasuk = QDateEdit(self)
        self.tglMasuk.setCalendarPopup(True)
        self.form.addRow("Tanggal Masuk", self.tglMasuk)

        self.harga = QLineEdit(self)
        self.harga.setPlaceholderText("Harga")
        self.form.addRow("Harga", self.harga)

        self.jumlah = QSpinBox(self)
        self.form.addRow("Masukkan Jumlah", self.jumlah)

        self.submit = QPushButton(self)
        self.submit.setText("Tambah")
        self.submit.clicked.connect(self.submit_btn)

        self.laporan = QPushButton(self)
        self.laporan.setText("Laporan")

        self.form.addRow(self.submit,self.laporan)
Ejemplo n.º 13
0
    def createReportBox(self):
        minDate, maxDate = self.selectMinAndMaxDate()
        minDate = QDate(minDate.year, minDate.month, minDate.day)
        maxDate = QDate(maxDate.year, maxDate.month, maxDate.day)

        self.fromDateEdit = QDateEdit()
        self.fromDateEdit.setDate(minDate)
        self.fromDateEdit.setDisplayFormat('d MMM yyyy')
        self.fromDateEdit.setAlignment(Qt.AlignHCenter)

        self.toDateEdit = QDateEdit()
        self.toDateEdit.setDate(maxDate)
        self.toDateEdit.setDisplayFormat('d MMM yyyy')
        self.toDateEdit.setAlignment(Qt.AlignHCenter)

        self.reportTypeComboBox = QComboBox()
        for item in reportTypes:
            self.reportTypeComboBox.addItem(item)

        monthlyButton = QPushButton("View")
        monthlyButton.clicked.connect(self.createReport)

        layout = QGridLayout()

        layout.addWidget(self.fromDateEdit,         0, 0, 1, 1)
        layout.addWidget(self.toDateEdit,           0, 1, 1, 1)
        layout.addWidget(self.reportTypeComboBox,   1, 0, 1, 1)
        layout.addWidget(monthlyButton,             1, 1, 1, 1)

        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)

        self.raportBox = QGroupBox("Charts")
        self.raportBox.setLayout(layout)
Ejemplo n.º 14
0
    def createFormGroupBox(self):
        self.formGroupBox = QGroupBox("Add Product")
        layout = QFormLayout()

        self.submit_btn = QPushButton("Submit")
        self.itemName = QLineEdit()
        self.qty = QLineEdit()

        self.expiry_date = QDateEdit()
        self.expiry_date.setCalendarPopup(True)
        self.expiry_date.setMinimumDate(QDate.currentDate())

        # yr = datetime.datetime.today().year
        # dt = QDate()
        # dt.getDate()

        self.price = QLineEdit()
        self.purchase_from = QLineEdit()
        self.GST = QLineEdit()
        layout.addRow(QLabel("Item Name:"), self.itemName)
        layout.addRow(QLabel("Quantity:"), self.qty)

        self.type_of_packing = QComboBox()
        self.type_of_packing.addItem("Packets")
        self.type_of_packing.addItem("Tablets")
        self.type_of_packing.addItem("Carton")
        layout.addRow(QLabel("Type"), self.type_of_packing)

        layout.addRow(QLabel("Expiry Date:"), self.expiry_date)
        layout.addRow(QLabel("Price:"), self.price)
        layout.addRow(QLabel("Purchase from:"), self.purchase_from)
        layout.addRow(QLabel("GST:"), self.GST)
        layout.addWidget(self.submit_btn)
        self.formGroupBox.setLayout(layout)
Ejemplo n.º 15
0
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create textbox

        self.label = QLabel('Nome Azione', self)
        self.label.move(100, 160)
        self.label.show()

        self.nome = QLineEdit(self)
        self.nome.move(300, 160)
        self.nome.show()

        self.dat1 = QDateEdit(self)
        self.dat1.move(500, 160)
        self.dat1.show()

        self.dat2 = QDateEdit(self)
        self.dat2.move(800, 160)
        self.dat2.show()

        # Create a button in the window
        self.button = QPushButton('Show text', self)
        self.button.move(400, 260)

        # connect button to function on_click
        self.button.clicked.connect(self.on_click)
        self.show()
Ejemplo n.º 16
0
        def createSearch(self):
            self.formGroupBox = QGroupBox("Search Form")
            self.formGroupBox1 = QGroupBox()
            layout = QFormLayout()

            self.fromText1 = QLineEdit()
            self.toText1 = QLineEdit()


            layout.addRow(QLabel("From:"), self.fromText1)
            layout.addRow(QLabel("To:"), self.toText1)

            defaultDate = QDate.currentDate().toPyDate()
            self.deptDate1 = QDateEdit(QDate(defaultDate.year, defaultDate.month, defaultDate.day))
            self.arrDate1 = QDateEdit(QDate(defaultDate.year, defaultDate.month, defaultDate.day))

            layout.addRow(QLabel("Departure Date:"), self.deptDate1)
            layout.addRow(QLabel("Arrival Date:"), self.arrDate1)

            defaultTime = QTime.currentTime().toPyTime()
            self.deptTime1 = QTimeEdit(QTime(defaultTime.hour, defaultTime.minute, defaultTime.second))
            self.arrTime2 = QTimeEdit(QTime(defaultTime.hour, defaultTime.minute, defaultTime.second))

            layout.addRow(QLabel("Departure Time:"), self.deptTime1)
            layout.addRow(QLabel("Arrival Time:"), self.arrTime2)
            self.formGroupBox.setLayout(layout)
Ejemplo n.º 17
0
    def create_choice_groupbox(self):
        gbox = QGroupBox()
        hbox = QHBoxLayout()
        vbox = QVBoxLayout()
        hbox2 = QHBoxLayout()

        # widget
        lbl_period = QLabel('조회기간')
        self.dateed_start = QDateEdit()
        lbl_mark = QLabel('~')
        self.dateed_end = QDateEdit()
        self.dateed_start.setDate(QDate.currentDate())
        self.dateed_end.setDate(QDate.currentDate())
        self.dateed_start.setCalendarPopup(True)
        self.dateed_end.setCalendarPopup(True)
        btn_week = QPushButton('1주')
        btn_view = QPushButton('조회')
        # Signal
        btn_week.clicked.connect(self.change_week_period)
        btn_view.clicked.connect(self.lookup_period_sales)

        hbox.addWidget(lbl_period)
        hbox.addWidget(self.dateed_start)
        hbox.addWidget(lbl_mark)
        hbox.addWidget(self.dateed_end)
        hbox2.addWidget(btn_week)
        hbox2.addWidget(btn_view)
        vbox.addLayout(hbox)
        vbox.addLayout(hbox2)
        gbox.setLayout(vbox)

        return gbox
Ejemplo n.º 18
0
    def tab_1(self):
        # main layout
        layout = QVBoxLayout()

        task_name = QLabel('Task Name')
        due_date = QLabel('Due Date')
        due_time = QLabel('Due Time')

        if (self.button_name == "Add"):
            self.task_name_input = QLineEdit()
            self.due_date_input = QDateEdit()
            self.due_date_input.setMinimumDate(QDate.currentDate())
            self.due_time_input = QTimeEdit()

        else:

            task_info = user_tasks.get_task(self.identifier)

            self.task_name_input = QLineEdit(task_info[1])
            self.due_date_input = QDateEdit(task_info[2].date())
            self.due_date_input.setMinimumDate(QDate.currentDate())
            self.due_time_input = QTimeEdit(task_info[2].time())

        layout.addWidget(task_name)
        layout.addWidget(self.task_name_input)
        layout.addWidget(due_date)
        layout.addWidget(self.due_date_input)
        layout.addWidget(due_time)
        layout.addWidget(self.due_time_input)
        layout.addSpacing(20)

        self.tabs.tab_1.setLayout(layout)
Ejemplo n.º 19
0
    def __init__(self, *args, **kwargs):
        super(ReceiptParserUI, self).__init__(*args, **kwargs)
        main_layout = QVBoxLayout()

        opt_layout = QHBoxLayout()
        self.current_date = QDateEdit(self)
        self.current_date.setDate(QDate.currentDate())
        self.current_date.setCalendarPopup(True)
        self.current_date.setDisplayFormat("yyyy-MM-dd")
        opt_layout.addWidget(self.current_date)

        self.parser_button = QPushButton("提取数据", self)
        opt_layout.addWidget(self.parser_button)

        self.message_label = QLabel("请在【后台管理】-【行业数据】-【交易所数据】获取仓单源文件后再提取", self)
        opt_layout.addWidget(self.message_label)

        opt_layout.addStretch()
        main_layout.addLayout(opt_layout)

        self.preview_table = QTableWidget(self)
        self.preview_table.setColumnCount(7)
        self.preview_table.setHorizontalHeaderLabels(
            ["仓库编号", "简称", "品种", "交易代码", "日期", "仓单", "增减"])
        main_layout.addWidget(self.preview_table)

        self.commit_button = QPushButton("提交保存", self)
        main_layout.addWidget(self.commit_button, alignment=Qt.AlignRight)
        self.setLayout(main_layout)
Ejemplo n.º 20
0
    def createDateSelection(self):
        '''Generate the area containing the date selectors'''

        self.dateSelectionGroupBox = QGroupBox(
            self.localization.date_selection)

        layout = QGridLayout()

        self.startDateEdit = QDateEdit(calendarPopup=True)
        self.startDateEdit.setDisplayFormat("dd.MM.yyyy")
        self.startDateEdit.setReadOnly(True)
        self.startDateEdit.lineEdit().setDisabled(True)

        self.endDateEdit = QDateEdit(calendarPopup=True)
        self.endDateEdit.setDisplayFormat("dd.MM.yyyy")
        self.endDateEdit.setReadOnly(True)
        self.endDateEdit.lineEdit().setDisabled(True)

        self.startTimeEdit = QLineEdit("00:00")
        self.endTimeEdit = QLineEdit("23:59")
        self.startTimeEdit.setDisabled(True)
        self.endTimeEdit.setDisabled(True)

        layout.addWidget(self.startDateEdit, 0, 0)
        layout.addWidget(self.startTimeEdit, 0, 1)

        layout.addWidget(self.endDateEdit, 1, 0)
        layout.addWidget(self.endTimeEdit, 1, 1)

        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)

        self.dateSelectionGroupBox.setLayout(layout)
Ejemplo n.º 21
0
    def initUI(self):
        self.mainLayout = QVBoxLayout()
        lineEditsGroup = QGroupBox()
        grid = QGridLayout()

        #Create line edit labels for each field except user ID (non-editable)
        for i, key in enumerate(['Name', 'Birthday', 'Gender', 'Nationality']):
            grid.addWidget(QLabel(key + "*"), i, 0)

        #Create name line entry
        self.nameEntry = QLineEdit(self)
        grid.addWidget(self.nameEntry, 0, 1)

        #Create birthday entry
        self.birthdayEntry = QDateEdit(self)
        grid.addWidget(self.birthdayEntry, 1, 1)

        #Create gender selection
        self.genderBox = QComboBox(self)
        self.genderBox.addItem("Male")
        self.genderBox.addItem("Female")
        self.genderBox.addItem("Other")
        grid.addWidget(self.genderBox, 2, 1)

        #Add nationality
        self.nationEntry = QLineEdit(self)
        grid.addWidget(self.nationEntry, 3, 1)

        lineEditsGroup.setLayout(grid)
        self.mainLayout.addWidget(lineEditsGroup)

        self.setLayout(self.mainLayout)
Ejemplo n.º 22
0
 def news_input(self):
     self.lab_all = QLabel('All news:', self)
     self.lab_search = QLabel('Search:', self)
     self.lab_by_date = QLabel('News by date:', self)
     self.txt_all = QLineEdit(self)
     self.txt_search = QLineEdit(self)
     self.exit_but = QPushButton('Exit')
     self.find_but = QPushButton('Find')
     self.find_but2 = QPushButton('Find')
     self.cal_but= QPushButton('Calendar')
     self.cal_but.clicked.connect(self.calendar)
     self.find_but.clicked.connect(self.find_news)
     self.find_but2.clicked.connect(self.find_by_words)
     self.exit_but.clicked.connect(self.close)
     self.date = QDateEdit(self)
     self.date.setDisplayFormat('dd/MM/yyyy')
     self.scroll_area=QScrollArea()#Создаем обект с горизонтальной и вертикальной полосой прокрутки
     self.scroll_area.setWidgetResizable(True)
     self.scroll_area.setVerticalScrollBarPolicy(2)#Вертикальная и горизонтальная полоса прокрутки будут вседа видны
     self.scroll_area.setHorizontalScrollBarPolicy(2)
     grid = QGridLayout()
     grid.setSpacing(1)
     grid.addWidget(self.lab_all, 1, 0, 1, 1)
     grid.addWidget(self.txt_all, 1, 1, 1, 1)
     grid.addWidget(self.date, 2, 1, 1, 1)
     grid.addWidget(self.cal_but, 2, 2, 1, 1)
     grid.addWidget(self.find_but, 2, 3, 1, 1)
     grid.addWidget(self.lab_by_date, 2, 0, 1, 1)
     grid.addWidget(self.lab_search, 3, 0, 1, 1)
     grid.addWidget(self.txt_search, 3, 1, 1, 2)
     grid.addWidget(self.find_but2, 3, 3, 1, 1)
     grid.addWidget(self.scroll_area, 4, 0, 1, 6)
     grid.addWidget(self.exit_but, 5, 5, 1, 1)
     self.setLayout(grid)
     self.txt_all.setText(str(len(self.news.keys())))
Ejemplo n.º 23
0
    def __init__(self, modeldb, parent=None):
        """Initialize the RaceInfo instance."""
        super().__init__(parent=parent)

        self.modeldb = modeldb

        # Cache this. We use it so often.
        self.race_table_model = self.modeldb.race_table_model

        self.name_lineedit = QLineEdit()
        self.date_dateedit = QDateEdit()
        self.date_dateedit.setCalendarPopup(True)
        self.notes_plaintextedit = QPlainTextEdit()
        self.notes_plaintextedit.setPlaceholderText(defaults.RACE_NOTES_PLACEHOLDER_TEXT)
        self.dataChanged(QModelIndex(), QModelIndex(), [Qt.DisplayRole])

        # Top-level widgets.
        self.setLayout(QFormLayout())
        self.layout().addRow('Race Name', self.name_lineedit)
        self.layout().addRow('Race Date', self.date_dateedit)
        self.layout().itemAt(self.layout().rowCount() - 1,
                             QFormLayout.LabelRole).setAlignment(Qt.AlignCenter)
        self.layout().addRow('Notes', self.notes_plaintextedit)

        # Signals/slots plumbing.
        self.race_table_model.dataChanged.connect(self.dataChanged)
        self.name_lineedit.editingFinished.connect(self.name_editing_finished)
        self.date_dateedit.editingFinished.connect(self.date_editing_finished)
Ejemplo n.º 24
0
    def __init__(self, parent=None):
        super(PredWindowSelect, self).__init__(parent)

        self.setTitle('Prediction Window Select')
        grid = QGridLayout()

        lbl_start = QLabel('Start Date: ')
        lbl_end = QLabel('End Date: ')

        self.deStart = QDateEdit()
        self.deStart.setEnabled(False)
        self.deStart.setCalendarPopup(True)
        self.deStart.dateChanged.connect(self.setEndDateMinimum)
        self.deEnd = QDateEdit()
        self.deEnd.setCalendarPopup(True)
        self.deEnd.dateChanged.connect(self.onEndDateChange)
        self.setEndDateMinimum()
        lbl_disc = QLabel(
            'Note: A minimum prediction window length <br>of 5 business days has been imposed.'
        )

        grid.addWidget(lbl_start, 0, 0)
        grid.addWidget(lbl_end, 1, 0)
        grid.addWidget(self.deStart, 0, 1)
        grid.addWidget(self.deEnd, 1, 1)
        grid.addWidget(lbl_disc, 2, 1)

        self.setLayout(grid)
Ejemplo n.º 25
0
    def __init__(self):
        super().__init__()

        self.Layout = QGridLayout(self)

        self.NameItem = QLineEdit(self)  #Linha para Digitar nome do produto
        self.Layout.addWidget(self.NameItem, 1, 0, 1, 2)
        self.NameItem.setPlaceholderText('Nome Item')
        self.NameItem.returnPressed.connect(lambda: self.CodBarra.setFocus())

        self.CodBarra = QLineEdit(self)
        self.Layout.addWidget(self.CodBarra, 2, 0, 1, 2)
        self.CodBarra.setPlaceholderText("Codigo Barra")
        self.CodBarra.returnPressed.connect(
            lambda: self.DateVencimento.setFocus())

        self.DateVencimento = QLabel('Vencimento:',
                                     self)  #Dia que o produto vence
        self.Layout.addWidget(self.DateVencimento, 3, 0, 1, 1)
        self.DateVencimento.setFixedWidth(100)

        self.Date = QDateEdit()
        datetimetext = QDateTime(date.today().year,
                                 date.today().month,
                                 date.today().day, 0, 0)
        self.Date.setDateTime(datetimetext)
        self.Layout.addWidget(self.Date, 3, 1, 1, 1)

        self.CadasterButton = QPushButton('Cadastrar Produto',
                                          self)  #Botao que Cadastra o Produto
        self.Layout.addWidget(self.CadasterButton, 4, 0, 1, 2)
        self.CadasterButton.clicked.connect(self.CadButton_Func)
Ejemplo n.º 26
0
 def keyPressEvent(self, event):
     if self.is_null():
         self.set_valor(QDate.currentDate())
         self.setSelectedSection(QDateEdit.DaySection)
     QDateEdit.keyPressEvent(self, event)
     if event.key() == Qt.Key_Delete:
         self.clear()
Ejemplo n.º 27
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        start_label = QLabel("Начало", self)
        self.start_edit = QDateEdit(calendarPopup=True)

        finish_label = QLabel("Конец", self)
        self.finish_edit = QDateEdit(calendarPopup=True)

        studyings_label = QLabel("Расписание", self)
        self.studyings_list = QListWidget(self)

        layout = QVBoxLayout()
        layout.addWidget(start_label)
        layout.addWidget(self.start_edit)
        layout.addWidget(finish_label)
        layout.addWidget(self.finish_edit)
        layout.addWidget(studyings_label)
        layout.addWidget(self.studyings_list)

        self.ok_btn = QPushButton('OK', parent=self)
        self.ok_btn.clicked.connect(self.ok)
        self.ok_cancel = QPushButton('Cancel', parent=self)
        self.ok_cancel.clicked.connect(self.cancel)

        btn_layout = QHBoxLayout()
        btn_layout.addWidget(self.ok_btn)
        btn_layout.addWidget(self.ok_cancel)

        layout.addLayout(btn_layout)
        layout.addStretch(0)

        self.setLayout(layout)

        self.presenter = SyllabusPresenter(self)
Ejemplo n.º 28
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.time_label = QLabel("Время начала", self)
        self.time_edit = QTimeEdit()

        self.date_label = QLabel("Дата", parent=self)
        self.date_edit = QDateEdit(calendarPopup=True)

        self.subjects_label = QLabel("Темы", self)
        self.subjects_list = QListWidget(self)

        layout = QVBoxLayout()
        layout.addWidget(self.time_label)
        layout.addWidget(self.time_edit)
        layout.addWidget(self.date_label)
        layout.addWidget(self.date_edit)
        layout.addWidget(self.subjects_label)
        layout.addWidget(self.subjects_list)

        self.ok_btn = QPushButton('OK', parent=self)
        self.ok_btn.clicked.connect(self.ok)
        self.ok_cancel = QPushButton('Cancel', parent=self)
        self.ok_cancel.clicked.connect(self.cancel)

        btn_layout = QHBoxLayout()
        btn_layout.addWidget(self.ok_btn)
        btn_layout.addWidget(self.ok_cancel)

        layout.addLayout(btn_layout)
        layout.addStretch(0)

        self.setLayout(layout)

        self.presenter = StudyingPresenter(self)
Ejemplo n.º 29
0
    def __init__(self, parent=None):
        super(HistWindowSelect, self).__init__(parent)

        self.setTitle('Historical Window Select')
        grid = QGridLayout()

        lbl_start = QLabel('Start Date: ')
        lbl_end = QLabel('End Date: ')

        self.deStart = QDateEdit()
        self.deStart.setCalendarPopup(True)
        self.deStart.setMinimumDateTime(dt.datetime(2015, 1, 1))
        self.deStart.setMaximumDateTime(
            self.getWeekdaysBack(dt.datetime.now(), 22))
        self.deStart.dateChanged.connect(self.onStartDateChange)
        self.deEnd = QDateEdit()
        self.deEnd.setCalendarPopup(True)
        self.deEnd.setMaximumDateTime(dt.datetime.now())
        self.deEnd.dateChanged.connect(self.onEndDateChange)
        self.setEndDateMinimum()
        lbl_disc = QLabel(
            'Note: A minimum historical window length <br>of 22 business days has been imposed.'
        )

        grid.addWidget(lbl_start, 0, 0)
        grid.addWidget(lbl_end, 1, 0)
        grid.addWidget(self.deStart, 0, 1)
        grid.addWidget(self.deEnd, 1, 1)
        grid.addWidget(lbl_disc, 2, 1)

        self.setLayout(grid)
Ejemplo n.º 30
0
    def __init__(self, parent):
        super(dateWidget, self).__init__(parent=parent)
        self.start = 0
        self.end = 0
        # --------------------------------------------------------------------
        # Date picker
        self.label_from = QLabel('From', parent)
        self.label_from.setAlignment(Qt.AlignCenter)
        self.label_from.setFont(QFont("Open Sans Bold", 12))
        self.label_from.setStyleSheet("background-color: rgb(134,194,50);"
                                      "color: rgb(255,255,255);")
        self.label_from.resize(100, 20)
        self.label_from.move(20, 60)

        self.d1 = QDateEdit(parent, calendarPopup=True)
        self.d1.setDateTime(QDateTime.currentDateTime())
        self.d1.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.d1.setGeometry(20, 80, 100, 25)
        #self.d1.dateChanged.connect(self.date_change)

        label_to = QLabel('To', parent)
        label_to.setAlignment(Qt.AlignCenter)
        label_to.setFont(QFont("Open Sans Bold", 12))
        label_to.setStyleSheet("background-color: rgb(134,194,50);"
                               "color: rgb(255,255,255);")
        label_to.resize(100, 20)
        label_to.move(140, 60)

        self.d2 = QDateEdit(parent, calendarPopup=True)
        self.d2.setDateTime(QDateTime.currentDateTime())
        self.d2.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.d2.setGeometry(140, 80, 100, 25)
Ejemplo n.º 31
0
        def layoutOne(self):
            QWidget().setLayout(self.layout())
            checkBtn = QCheckBox("Return")
            self.formGroupBox = QGroupBox("Search Form")
            self.formGroupBox1 = QGroupBox()
            layout = QFormLayout()

            self.fromText1 = QLineEdit()
            self.toText1 = QLineEdit()

            defaultDate = QDate.currentDate().toPyDate()
            layout.addRow(QLabel("From:"), self.fromText1)
            layout.addRow(QLabel("To:"), self.toText1)

            self.deptDate1 = QDateEdit(QDate(defaultDate.year, defaultDate.month, defaultDate.day))
            self.arrDate1 = QDateEdit(QDate(defaultDate.year, defaultDate.month, defaultDate.day))

            layout.addRow(QLabel("Departure Date:"), self.deptDate1)
            layout.addRow(QLabel("Arrival Date:"), self.arrDate1)

            defaultTime = QTime.currentTime().toPyTime()
            self.deptTime1 = QTimeEdit(QTime(defaultTime.hour, defaultTime.minute, defaultTime.second))
            self.arrTime2 = QTimeEdit(QTime(defaultTime.hour, defaultTime.minute, defaultTime.second))

            layout.addRow(QLabel("Departure Time:"), self.deptTime1)
            layout.addRow(QLabel("Arrival Time:"), self.arrTime2)
            self.formGroupBox.setLayout(layout)
            checkBtn.stateChanged.connect(self.transform)
    def __init__(self):
        super().__init__()

        # Make widgets #################

        self.edit1 = QDateEdit()
        self.edit2 = QDateEdit()
        self.edit3 = QDateEdit()

        self.edit1.setMinimumDate(datetime.date(year=2017, month=9, day=1))
        self.edit2.setMinimumDate(datetime.date(year=2017, month=9, day=1))
        self.edit3.setMinimumDate(datetime.date(year=2017, month=9, day=1))

        self.edit1.setMaximumDate(datetime.date(year=2020, month=9, day=1))
        self.edit2.setMaximumDate(datetime.date(year=2020, month=9, day=1))
        self.edit3.setMaximumDate(datetime.date(year=2020, month=9, day=1))

        self.edit1.setDate(datetime.datetime.now().date())
        self.edit2.setDate(datetime.datetime.now().date())
        self.edit3.setDate(datetime.datetime.now().date())

        self.edit1.setCalendarPopup(True)
        self.edit2.setCalendarPopup(True)
        self.edit3.setCalendarPopup(True)

        # Format: see http://doc.qt.io/qt-5/qdatetime.html#toString-2
        self.edit1.setDisplayFormat("yyyy-MM-dd")
        self.edit2.setDisplayFormat("dd/MM/yyyy")
        self.edit3.setDisplayFormat("dddd d MMMM yyyy")

        self.btn = QPushButton("Print")

        # Set button slot ##############

        self.btn.clicked.connect(self.printText)

        # Set the layout ###############

        vbox = QVBoxLayout()

        vbox.addWidget(self.edit1)
        vbox.addWidget(self.edit2)
        vbox.addWidget(self.edit3)

        vbox.addWidget(self.btn)

        self.setLayout(vbox)
Ejemplo n.º 33
0
    def createDatesGroupBox(self):
        self.datesGroupBox = QGroupBox(self.tr("Dates"))

        self.minimumDateEdit = QDateEdit()
        self.minimumDateEdit.setDisplayFormat('MMM d yyyy')
        self.minimumDateEdit.setDateRange(self.calendar.minimumDate(),
                                          self.calendar.maximumDate())
        self.minimumDateEdit.setDate(self.calendar.minimumDate())

        self.minimumDateLabel = QLabel("&Minimum Date:")
        self.minimumDateLabel.setBuddy(self.minimumDateEdit)

        self.currentDateEdit = QDateEdit()
        self.currentDateEdit.setDisplayFormat('MMM d yyyy')
        self.currentDateEdit.setDate(self.calendar.selectedDate())
        self.currentDateEdit.setDateRange(self.calendar.minimumDate(),
                self.calendar.maximumDate())

        self.currentDateLabel = QLabel("&Current Date:")
        self.currentDateLabel.setBuddy(self.currentDateEdit)

        self.maximumDateEdit = QDateEdit()
        self.maximumDateEdit.setDisplayFormat('MMM d yyyy')
        self.maximumDateEdit.setDateRange(self.calendar.minimumDate(),
                self.calendar.maximumDate())
        self.maximumDateEdit.setDate(self.calendar.maximumDate())

        self.maximumDateLabel = QLabel("Ma&ximum Date:")
        self.maximumDateLabel.setBuddy(self.maximumDateEdit)

        self.currentDateEdit.dateChanged.connect(self.calendar.setSelectedDate)
        self.calendar.selectionChanged.connect(self.selectedDateChanged)
        self.minimumDateEdit.dateChanged.connect(self.minimumDateChanged)
        self.maximumDateEdit.dateChanged.connect(self.maximumDateChanged)
 
        dateBoxLayout = QGridLayout()
        dateBoxLayout.addWidget(self.currentDateLabel, 1, 0)
        dateBoxLayout.addWidget(self.currentDateEdit, 1, 1)
        dateBoxLayout.addWidget(self.minimumDateLabel, 0, 0)
        dateBoxLayout.addWidget(self.minimumDateEdit, 0, 1)
        dateBoxLayout.addWidget(self.maximumDateLabel, 2, 0)
        dateBoxLayout.addWidget(self.maximumDateEdit, 2, 1)
        dateBoxLayout.setRowStretch(3, 1)

        self.datesGroupBox.setLayout(dateBoxLayout)
Ejemplo n.º 34
0
    def createDateTimeEdits(self):
        self.editsGroup = QGroupBox("Date and time spin boxes")

        dateLabel = QLabel()
        dateEdit = QDateEdit(QDate.currentDate())
        dateEdit.setDateRange(QDate(2005, 1, 1), QDate(2010, 12, 31))
        dateLabel.setText("Appointment date (between %s and %s):" %
                    (dateEdit.minimumDate().toString(Qt.ISODate),
                    dateEdit.maximumDate().toString(Qt.ISODate)))

        timeLabel = QLabel()
        timeEdit = QTimeEdit(QTime.currentTime())
        timeEdit.setTimeRange(QTime(9, 0, 0, 0), QTime(16, 30, 0, 0))
        timeLabel.setText("Appointment time (between %s and %s):" %
                    (timeEdit.minimumTime().toString(Qt.ISODate),
                    timeEdit.maximumTime().toString(Qt.ISODate)))

        self.meetingLabel = QLabel()
        self.meetingEdit = QDateTimeEdit(QDateTime.currentDateTime())

        formatLabel = QLabel("Format string for the meeting date and time:")

        formatComboBox = QComboBox()
        formatComboBox.addItem('yyyy-MM-dd hh:mm:ss (zzz \'ms\')')
        formatComboBox.addItem('hh:mm:ss MM/dd/yyyy')
        formatComboBox.addItem('hh:mm:ss dd/MM/yyyy')
        formatComboBox.addItem('hh:mm:ss')
        formatComboBox.addItem('hh:mm ap')

        formatComboBox.activated[str].connect(self.setFormatString)

        self.setFormatString(formatComboBox.currentText())

        editsLayout = QVBoxLayout()
        editsLayout.addWidget(dateLabel)
        editsLayout.addWidget(dateEdit)
        editsLayout.addWidget(timeLabel)
        editsLayout.addWidget(timeEdit)
        editsLayout.addWidget(self.meetingLabel)
        editsLayout.addWidget(self.meetingEdit)
        editsLayout.addWidget(formatLabel)
        editsLayout.addWidget(formatComboBox)
        self.editsGroup.setLayout(editsLayout)
Ejemplo n.º 35
0
    def __init__(self, model):
        super().__init__()
        self.header = QLabel('')
        self.desc = QLineEdit()
        self.date = QDateEdit()
        self.time = QTimeEdit()
        self.init_ui()

        self.mapper = QDataWidgetMapper()
        self.mapper.setModel(model)
        self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit)
        self.mapper.addMapping(self.desc, TaskModel.col_desc)
        self.mapper.addMapping(self.date, TaskModel.col_date)
        self.mapper.addMapping(self.time, TaskModel.col_time)
Ejemplo n.º 36
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.lastyear = int(time.strftime('%Y', time.localtime(time.time()))) - 1
        self.in_parameters = {u'datetime': str(self.lastyear) + u'年',
                              u'target_area': u'绍兴市',
                              u'density_cell': u'10',
                              u'density_class': 10,
                              u'day_cell': u'15',
                              u'day_class': 10,
                              u'out_type': u'tiff'}
        self.setupUi()

    def setupUi(self):
        self.setObjectName("MainWindow")
        self.setFixedSize(1040, 915)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        icon = QIcon()
        icon.addPixmap(QPixmap('./resource/weather-thunder.png'),QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.centralwidget = QWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setObjectName("centralwidget")
        self.layoutWidget = QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QRect(32, 10, 979, 851))
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout_5 =QVBoxLayout(self.layoutWidget)
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.datetime_label = QLabel(self.layoutWidget)
        self.datetime_label.setObjectName("datetime_label")
        self.horizontalLayout.addWidget(self.datetime_label)
        self.datetime = QDateEdit(self.layoutWidget)
        self.datetime.setDateTime(QDateTime(QDate(self.lastyear, 1, 1), QTime(0, 0, 0)))
        self.datetime.setObjectName("datetime")
        self.horizontalLayout.addWidget(self.datetime)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.target_area_label = QLabel(self.layoutWidget)
        self.target_area_label.setObjectName("target_area_label")
        self.horizontalLayout.addWidget(self.target_area_label)
        self.target_area = QComboBox(self.layoutWidget)
        self.target_area.setObjectName("target_area")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.horizontalLayout.addWidget(self.target_area)
        spacerItem2 = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.verticalLayout_5.addLayout(self.horizontalLayout)
        self.tabWidget = QTabWidget(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
        self.tabWidget.setSizePolicy(sizePolicy)
        self.tabWidget.setObjectName("tabWidget")
        self.density_tab = QWidget()
        self.density_tab.setObjectName("density_tab")
        self.verticalLayout_3 =QVBoxLayout(self.density_tab)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.verticalLayout_2 =QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.density_cell_label = QLabel(self.density_tab)
        self.density_cell_label.setObjectName("density_cell_label")
        self.horizontalLayout_2.addWidget(self.density_cell_label)
        self.density_cell = QSpinBox(self.density_tab)
        self.density_cell.setProperty("value", 10)
        self.density_cell.setObjectName("density_cell")
        self.horizontalLayout_2.addWidget(self.density_cell)
        spacerItem3 = QSpacerItem(40, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem3)
        self.density_class_label = QLabel(self.density_tab)
        self.density_class_label.setObjectName("density_class_label")
        self.horizontalLayout_2.addWidget(self.density_class_label)
        self.density_class = QSpinBox(self.density_tab)
        self.density_class.setProperty("value", 10)
        self.density_class.setObjectName("density_class")
        self.horizontalLayout_2.addWidget(self.density_class)
        spacerItem4 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem4)
        self.density_mxd = QPushButton(self.density_tab)
        self.density_mxd.setObjectName("density_mxd")
        self.horizontalLayout_2.addWidget(self.density_mxd)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.density_view = QGraphicsView(self.density_tab)
        self.density_view.setObjectName("density_view")
        self.verticalLayout_2.addWidget(self.density_view)
        self.verticalLayout_3.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.density_tab, "")
        self.day_tab = QWidget()
        self.day_tab.setObjectName("day_tab")
        self.verticalLayout_4 =QVBoxLayout(self.day_tab)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.verticalLayout =QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_3 =QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.day_cell_label = QLabel(self.day_tab)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.day_cell_label.sizePolicy().hasHeightForWidth())
        self.day_cell_label.setSizePolicy(sizePolicy)
        self.day_cell_label.setObjectName("day_cell_label")
        self.horizontalLayout_3.addWidget(self.day_cell_label)
        self.day_cell = QSpinBox(self.day_tab)
        self.day_cell.setProperty("value", 15)
        self.day_cell.setObjectName("day_cell")
        self.horizontalLayout_3.addWidget(self.day_cell)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem5)
        self.day_class_label = QLabel(self.day_tab)
        self.day_class_label.setObjectName("day_class_label")
        self.horizontalLayout_3.addWidget(self.day_class_label)
        self.day_class = QSpinBox(self.day_tab)
        self.day_class.setProperty("value", 10)
        self.day_class.setObjectName("day_class")
        self.horizontalLayout_3.addWidget(self.day_class)
        spacerItem6 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem6)
        self.day_mxd = QPushButton(self.day_tab)
        self.day_mxd.setObjectName("day_mxd")
        self.horizontalLayout_3.addWidget(self.day_mxd)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.day_view = QGraphicsView(self.day_tab)
        self.day_view.setObjectName("day_view")
        self.verticalLayout.addWidget(self.day_view)
        self.verticalLayout_4.addLayout(self.verticalLayout)
        self.tabWidget.addTab(self.day_tab, "")
        self.verticalLayout_5.addWidget(self.tabWidget)
        self.horizontalLayout_4 =QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.progressBar = QProgressBar(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth())
        self.progressBar.setSizePolicy(sizePolicy)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout_4.addWidget(self.progressBar)
        self.execute_button = QPushButton(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.execute_button.sizePolicy().hasHeightForWidth())
        self.execute_button.setSizePolicy(sizePolicy)
        self.execute_button.setObjectName("execute_button")
        self.horizontalLayout_4.addWidget(self.execute_button)
        self.verticalLayout_5.addLayout(self.horizontalLayout_4)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 1040, 26))
        self.menubar.setObjectName("menubar")
        self.file_menu = QMenu(self.menubar)
        self.file_menu.setObjectName("file_menu")
        self.help_menu = QMenu(self.menubar)
        self.help_menu.setObjectName("help_menu")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.action_add_data = QAction(self)
        self.action_add_data.setObjectName("action_add_data")
        self.action_help = QAction(self)
        self.action_help.setObjectName("action_help")
        self.action_about = QAction(self)
        self.action_about.setObjectName("action_about")
        self.action_save_pic = QAction(self)
        self.action_save_pic.setObjectName("action_save_pic")
        self.file_menu.addAction(self.action_add_data)
        self.file_menu.addAction(self.action_save_pic)
        self.help_menu.addAction(self.action_help)
        self.help_menu.addAction(self.action_about)
        self.menubar.addAction(self.file_menu.menuAction())
        self.menubar.addAction(self.help_menu.menuAction())

        self.retranslateUi()
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(self)
        self.center()
        self.show()

        self.target_area.activated[str].connect(self.updateTargetArea)
        self.datetime.dateChanged.connect(self.updateDatetime)
        self.density_cell.valueChanged.connect(self.updateDensityCell)
        self.density_class.valueChanged.connect(self.updateDensityClass)
        self.day_cell.valueChanged.connect(self.updateDayCell)
        self.day_class.valueChanged.connect(self.updateDayClass)

        self.action_add_data.triggered.connect(self.addData)
        self.action_save_pic.triggered.connect(self.savePic)
        self.action_about.triggered.connect(self.showAbout)
        self.action_help.triggered.connect(self.showHelp)
        self.execute_button.clicked.connect(self.execute)
        self.density_mxd.clicked.connect(self.openMxdDensity)
        self.day_mxd.clicked.connect(self.openMxdDay)


        self.density_mxd.setDisabled(True)
        self.day_mxd.setDisabled(True)
        self.action_save_pic.setDisabled(True)

    def execute(self):
        dir = u"E:/Documents/工作/雷电公报/闪电定位原始文本数据/" + self.in_parameters[u'datetime']

        if os.path.exists(dir):
            datafiles = os.listdir(dir)
            datafiles = map(lambda x:os.path.join(dir,x),datafiles)
            self.in_parameters[u'origin_data_path'] = datafiles

        if not self.in_parameters.has_key(u'origin_data_path'):
            message = u"请加载%s的数据" % self.in_parameters[u'datetime']
            msgBox = QMessageBox()
            msgBox.setText(message)
            msgBox.setIcon(QMessageBox.Information)
            icon = QIcon()
            icon.addPixmap(QPixmap('./resource/weather-thunder.png'), QIcon.Normal, QIcon.Off)
            msgBox.setWindowIcon(icon)
            msgBox.setWindowTitle(" ")
            msgBox.exec_()
            return

        self.execute_button.setDisabled(True)
        self.execute_button.setText(u'正在制图中……')
        self.progressBar.setMaximum(0)
        self.progressBar.setMinimum(0)

        self.action_add_data.setDisabled(True)
        self.target_area.setDisabled(True)
        self.datetime.setDisabled(True)
        self.density_cell.setDisabled(True)
        self.density_class.setDisabled(True)
        self.day_cell.setDisabled(True)
        self.day_class.setDisabled(True)

        # for outfile in self.in_parameters[u'origin_data_path']:
        #     infile =
        #     try:
        #         with open(infile, 'w+') as in_f:
        #             for line in in_f:
        #                 line = line.replace(u":",":")
        #                 in_f.write(line)
        #     except Exception,inst:
        #         print infile

        self.process_thread = WorkThread()
        self.process_thread.trigger.connect(self.finished)
        self.process_thread.beginRun(self.in_parameters)

    def finished(self):

        #绘制闪电密度图
        ##清除上一次的QGraphicsView对象,防止其记录上一次图片结果,影响显示效果
        self.density_view.setAttribute(Qt.WA_DeleteOnClose)
        self.verticalLayout_2.removeWidget(self.density_view)
        size = self.density_view.size()
        self.density_view.close()

        self.density_view = QGraphicsView(self.density_tab)
        self.density_view.setObjectName("density_view")
        self.density_view.resize(size)
        self.verticalLayout_2.addWidget(self.density_view)

        densityPic = ''.join([cwd,u'/bulletinTemp/',
            self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'闪电密度空间分布.tif'])

        scene = QGraphicsScene()
        pixmap_density = QPixmap(densityPic)
        scene.addPixmap(pixmap_density)
        self.density_view.setScene(scene)
        scale = float(self.density_view.width()) / pixmap_density.width()
        self.density_view.scale(scale, scale)

        #绘制雷暴日图
        self.day_view.setAttribute(Qt.WA_DeleteOnClose)
        self.verticalLayout.removeWidget(self.day_view)
        size = self.day_view.size()
        self.day_view.close()

        self.day_view = QGraphicsView(self.day_tab)
        self.day_view.setObjectName("day_view")
        self.day_view.resize(size)
        self.verticalLayout.addWidget(self.day_view)

        dayPic = ''.join([cwd,u'/bulletinTemp/',
            self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif'])

        pixmap_day = QPixmap(dayPic)
        scene = QGraphicsScene()
        scene.addPixmap(pixmap_day)
        self.day_view.resize(self.density_view.width(),self.density_view.height())
        self.day_view.setScene(scene)
        scale = float(self.day_view.width()) / pixmap_day.width()
        self.day_view.scale(scale, scale)

        #处理进度条和执行按钮状态
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(100)
        self.progressBar.setFormat(u'完成!')
        self.execute_button.setDisabled(False)
        self.execute_button.setText(u'执行')
        #改变一些控件的状态
        self.action_add_data.setDisabled(False)
        self.target_area.setDisabled(False)
        self.datetime.setDisabled(False)
        self.density_cell.setDisabled(False)
        self.density_class.setDisabled(False)
        self.day_cell.setDisabled(False)
        self.day_class.setDisabled(False)
        self.density_mxd.setDisabled(False)
        self.day_mxd.setDisabled(False)
        self.action_save_pic.setDisabled(False)

    def addData(self):
        fnames = QFileDialog.getOpenFileNames(self, u'请选择原始的电闪数据',
                                              u'E:/Documents/工作/雷电公报/闪电定位原始文本数据',
                                              'Text files (*.txt);;All(*.*)')

        self.in_parameters[u'origin_data_path'] = fnames[0]

    def savePic(self):
        densityPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'闪电密度空间分布.tif'])

        dayPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif'])

        directory = QFileDialog.getExistingDirectory(self,u'请选择图片保存位置',
                                                     u'E:/Documents/工作/雷电公报',
                                    QFileDialog.ShowDirsOnly|QFileDialog.DontResolveSymlinks)

        dest_density = os.path.join(directory,os.path.basename(densityPic))
        dest_day = os.path.join(directory,os.path.basename(dayPic))

        if os.path.isfile(dest_day) or os.path.isfile(dest_density):
            message = u"文件已经存在!"
            msgBox = QMessageBox()
            msgBox.setText(message)
            msgBox.setIcon(QMessageBox.Information)
            icon = QIcon()
            icon.addPixmap(QPixmap("./resource/weather-thunder.png"), QIcon.Normal, QIcon.Off)
            msgBox.setWindowIcon(icon)
            msgBox.setWindowTitle(" ")
            msgBox.exec_()
            return

        move(dayPic,directory)
        move(densityPic,directory)

    def openMxdDay(self):
        program  = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe'
        src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb'])
        dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']])
        src_file = ''.join([self.in_parameters[u'target_area'] , u"地闪雷暴日空间分布模板.mxd"])

        copy(os.path.join(src_dir,src_file),dest_dir)

        arguments = [os.path.join(dest_dir,src_file)]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def openMxdDensity(self):
        program  = u'C:/Program Files (x86)/ArcGIS/Desktop10.3/bin/ArcMap.exe'
        src_dir = ''.join([cwd,u'/data/LightningBulletin.gdb'])
        dest_dir = ''.join([cwd,u"/bulletinTemp/",self.in_parameters[u'datetime'], u"/" , self.in_parameters[u'target_area']])
        src_file = ''.join([self.in_parameters[u'target_area'] ,u"闪电密度空间分布模板.mxd"])


        copy(os.path.join(src_dir,src_file),dest_dir)

        arguments = [os.path.join(dest_dir,src_file)]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def showAbout(self):
        self.about = About_Dialog()

    def showHelp(self):
        program  = u'C:/Windows/hh.exe'
        arguments = [''.join([cwd,'/help/help.CHM'])]
        self.process = QProcess(self)
        self.process.start(program,arguments)

    def updateTargetArea(self, area):
        self.in_parameters[u'target_area'] = area

    def updateDatetime(self, date):
        self.in_parameters[u'datetime'] = str(date.year()) + u'年'
        if self.in_parameters.has_key(u'origin_data_path'):
            self.in_parameters.__delitem__(u'origin_data_path')

    def updateDensityCell(self, cell):
        self.in_parameters[u'density_cell'] = str(cell)

    def updateDensityClass(self, nclass):
        self.in_parameters[u'density_class'] = nclass

    def updateDayCell(self, cell):
        self.in_parameters[u'day_cell'] = str(cell)


    def updateDayClass(self, nclass):
        self.in_parameters[u'day_class'] = nclass

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("MainWindow", "绍兴防雷中心 雷电公报制图"))
        self.datetime_label.setText(_translate("MainWindow", "年份"))
        self.datetime.setDisplayFormat(_translate("MainWindow", "yyyy"))
        self.target_area_label.setText(_translate("MainWindow", "地区"))
        self.target_area.setItemText(0, _translate("MainWindow", "绍兴市"))
        self.target_area.setItemText(1, _translate("MainWindow", "柯桥区"))
        self.target_area.setItemText(2, _translate("MainWindow", "上虞区"))
        self.target_area.setItemText(3, _translate("MainWindow", "诸暨市"))
        self.target_area.setItemText(4, _translate("MainWindow", "嵊州市"))
        self.target_area.setItemText(5, _translate("MainWindow", "新昌县"))
        self.density_cell_label.setText(_translate("MainWindow", "插值网格大小"))
        self.density_class_label.setText(_translate("MainWindow", "制图分类数目"))
        self.density_mxd.setText(_translate("MainWindow", "ArcGIS文档"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.density_tab), _translate("MainWindow", "电闪密度"))
        self.day_cell_label.setText(_translate("MainWindow", "插值网格大小"))
        self.day_class_label.setText(_translate("MainWindow", "制图分类数目"))
        self.day_mxd.setText(_translate("MainWindow", "ArcGIS文档"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.day_tab), _translate("MainWindow", "雷暴日"))
        self.execute_button.setText(_translate("MainWindow", "执行"))
        self.file_menu.setTitle(_translate("MainWindow", "文件"))
        self.help_menu.setTitle(_translate("MainWindow", "帮助"))
        self.action_add_data.setText(_translate("MainWindow", "加载数据"))
        self.action_help.setText(_translate("MainWindow", "使用说明"))
        self.action_about.setText(_translate("MainWindow", "关于"))
        self.action_save_pic.setText(_translate("MainWindow", "图片另存为"))
Ejemplo n.º 37
0
    def __init__(self):
        super(Window, self).__init__()

        self.proxyModel = MySortFilterProxyModel(self)
        self.proxyModel.setDynamicSortFilter(True)

        self.sourceView = QTreeView()
        self.sourceView.setRootIsDecorated(False)
        self.sourceView.setAlternatingRowColors(True)

        sourceLayout = QHBoxLayout()
        sourceLayout.addWidget(self.sourceView)
        sourceGroupBox = QGroupBox("Original Model")
        sourceGroupBox.setLayout(sourceLayout)

        self.filterCaseSensitivityCheckBox = QCheckBox("Case sensitive filter")
        self.filterCaseSensitivityCheckBox.setChecked(True)
        self.filterPatternLineEdit = QLineEdit()
        self.filterPatternLineEdit.setText("Grace|Sports")
        filterPatternLabel = QLabel("&Filter pattern:")
        filterPatternLabel.setBuddy(self.filterPatternLineEdit)
        self.filterSyntaxComboBox = QComboBox()
        self.filterSyntaxComboBox.addItem("Regular expression", QRegExp.RegExp)
        self.filterSyntaxComboBox.addItem("Wildcard", QRegExp.Wildcard)
        self.filterSyntaxComboBox.addItem("Fixed string", QRegExp.FixedString)
        self.fromDateEdit = QDateEdit()
        self.fromDateEdit.setDate(QDate(2006, 12, 22))
        self.fromDateEdit.setCalendarPopup(True)
        fromLabel = QLabel("F&rom:")
        fromLabel.setBuddy(self.fromDateEdit)
        self.toDateEdit = QDateEdit()
        self.toDateEdit.setDate(QDate(2007, 1, 5))
        self.toDateEdit.setCalendarPopup(True)
        toLabel = QLabel("&To:")
        toLabel.setBuddy(self.toDateEdit)

        self.filterPatternLineEdit.textChanged.connect(self.textFilterChanged)
        self.filterSyntaxComboBox.currentIndexChanged.connect(self.textFilterChanged)
        self.filterCaseSensitivityCheckBox.toggled.connect(self.textFilterChanged)
        self.fromDateEdit.dateChanged.connect(self.dateFilterChanged)
        self.toDateEdit.dateChanged.connect(self.dateFilterChanged)

        self.proxyView = QTreeView()
        self.proxyView.setRootIsDecorated(False)
        self.proxyView.setAlternatingRowColors(True)
        self.proxyView.setModel(self.proxyModel)
        self.proxyView.setSortingEnabled(True)
        self.proxyView.sortByColumn(1, Qt.AscendingOrder)

        self.textFilterChanged()
        self.dateFilterChanged()

        proxyLayout = QGridLayout()
        proxyLayout.addWidget(self.proxyView, 0, 0, 1, 3)
        proxyLayout.addWidget(filterPatternLabel, 1, 0)
        proxyLayout.addWidget(self.filterPatternLineEdit, 1, 1)
        proxyLayout.addWidget(self.filterSyntaxComboBox, 1, 2)
        proxyLayout.addWidget(self.filterCaseSensitivityCheckBox, 2, 0, 1, 3)
        proxyLayout.addWidget(fromLabel, 3, 0)
        proxyLayout.addWidget(self.fromDateEdit, 3, 1, 1, 2)
        proxyLayout.addWidget(toLabel, 4, 0)
        proxyLayout.addWidget(self.toDateEdit, 4, 1, 1, 2)
        proxyGroupBox = QGroupBox("Sorted/Filtered Model")
        proxyGroupBox.setLayout(proxyLayout)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(sourceGroupBox)
        mainLayout.addWidget(proxyGroupBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Custom Sort/Filter Model")
        self.resize(500, 450)
Ejemplo n.º 38
0
class MainWindow(QWidget):

    articleInfoUpdate = pyqtSignal()
    entityUpdate = pyqtSignal()
    crawlerUpdate = pyqtSignal()

    def __init__(self):
        super(MainWindow, self).__init__()

        self.initUI()

        self.articleInfoUpdate.connect(self.updateArticleInfo)
        self.entityUpdate.connect(self.updateEntityList)

    def initUI(self):
        self.setGeometry(0, 0, 500, 700)

        self.center()
        self.setWindowTitle('PView')

        mainLayout = QVBoxLayout()

        self.createArticleInfoBox()
        self.createViewArticleBox()
        self.createEntityBox()
        self.createReportBox()
        self.createDatabaseBox()

        mainLayout.addWidget(self.infoBox)
        mainLayout.addWidget(self.viewArticleBox)
        mainLayout.addWidget(self.entityBox)
        mainLayout.addWidget(self.raportBox)
        mainLayout.addWidget(self.databaseBox)

        self.setLayout(mainLayout)

        self.show()

    def createArticleInfoBox(self):
        self.articleCount = self.selectCountArticles()
        entityCount = self.selectCountEntities()
        associationsCount = self.selectCountAssociations()
        classifiedCount = self.selectCountClassifiedAssociations()

        label = "Number of articles: " + str(self.articleCount)
        self.articleCountLabel = QLabel(label)

        label = "Number of entities: " + str(entityCount)
        self.entitiesCountLabel = QLabel(label)

        label = "Number of associations: " + str(associationsCount)
        self.associationsCountLabel = QLabel(label)

        label = "Number of classified associations: " + str(classifiedCount)
        self.classifiedCountLabel = QLabel(label)

        layout = QVBoxLayout()
        layout.addWidget(self.articleCountLabel)
        layout.addWidget(self.entitiesCountLabel)
        layout.addWidget(self.associationsCountLabel)
        layout.addWidget(self.classifiedCountLabel)

        self.infoBox = QGroupBox("Statistics")
        self.infoBox.setLayout(layout)

    def createCrawlerBox(self):
        self.crawlButton = QPushButton("Crawl")
        self.crawlButton.setFocusPolicy(Qt.NoFocus)

        self.websiteList = QComboBox()
        self.websiteList.addItem("HotNews")

        layout = QGridLayout()

        layout.addWidget(self.websiteList, 0, 0, 1, 1)
        layout.addWidget(self.crawlButton, 0, 1, 1, 1)

        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)

        self.crawlerBox = QGroupBox("Crawler")
        self.crawlerBox.setLayout(layout)

    def createViewArticleBox(self):
        self.articleNumberLineEdit = QLineEdit("")
        self.articleNumberLineEdit.setAlignment(Qt.AlignHCenter)

        self.viewArticleButton = QPushButton("Open")
        self.viewArticleButton.clicked.connect(self.viewArticle)

        layout = QGridLayout()

        layout.addWidget(self.articleNumberLineEdit, 0, 0, 1, 1)
        layout.addWidget(self.viewArticleButton, 0, 1, 1, 1)

        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)

        self.viewArticleBox = QGroupBox("View Article")
        self.viewArticleBox.setLayout(layout)

    def createReportBox(self):
        minDate, maxDate = self.selectMinAndMaxDate()
        minDate = QDate(minDate.year, minDate.month, minDate.day)
        maxDate = QDate(maxDate.year, maxDate.month, maxDate.day)

        self.fromDateEdit = QDateEdit()
        self.fromDateEdit.setDate(minDate)
        self.fromDateEdit.setDisplayFormat('d MMM yyyy')
        self.fromDateEdit.setAlignment(Qt.AlignHCenter)

        self.toDateEdit = QDateEdit()
        self.toDateEdit.setDate(maxDate)
        self.toDateEdit.setDisplayFormat('d MMM yyyy')
        self.toDateEdit.setAlignment(Qt.AlignHCenter)

        self.reportTypeComboBox = QComboBox()
        for item in reportTypes:
            self.reportTypeComboBox.addItem(item)

        monthlyButton = QPushButton("View")
        monthlyButton.clicked.connect(self.createReport)

        layout = QGridLayout()

        layout.addWidget(self.fromDateEdit,         0, 0, 1, 1)
        layout.addWidget(self.toDateEdit,           0, 1, 1, 1)
        layout.addWidget(self.reportTypeComboBox,   1, 0, 1, 1)
        layout.addWidget(monthlyButton,             1, 1, 1, 1)

        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)

        self.raportBox = QGroupBox("Charts")
        self.raportBox.setLayout(layout)

    def createEntityBox(self):
        rows = self.selectCountEntities()

        self.entityList = QListWidget()
        entities = self.selectAllEntities()
        for entity in entities:
            self.doAssociationsForEntity(entity[1])
            self.entityList.addItem(entity[1])

        addButton = QPushButton("Add")
        addButton.clicked.connect(self.addEntity)

        removeButton = QPushButton("Delete")
        removeButton.clicked.connect(self.removeEntity)

        self.addEntityLineEdit = QLineEdit("")
        viewArticlesButton = QPushButton("View articles")
        viewArticlesButton.clicked.connect(self.viewArticleByEntity)

        self.algorithmComboBox = QComboBox()
        for key in classifiers.keys():
            self.algorithmComboBox.addItem(key)

        classifyButton = QPushButton("Classify")
        classifyButton.clicked.connect(self.classifyAllAssociations)

        layout = QGridLayout()
        layout.addWidget(self.entityList,           0, 0, 1, 4)
        layout.addWidget(self.addEntityLineEdit,    1, 0, 1, 2)
        layout.addWidget(addButton,                 1, 2, 1, 1)
        layout.addWidget(removeButton,              1, 3, 1, 1)
        layout.addWidget(viewArticlesButton,        2, 0, 1, 4)
        layout.addWidget(self.algorithmComboBox,    3, 0, 1, 2)
        layout.addWidget(classifyButton,            3, 2, 1, 2)

        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)
        layout.setColumnStretch(2, 1)
        layout.setColumnStretch(3, 1)

        self.entityBox = QGroupBox("Entities")
        self.entityBox.setLayout(layout)

    def createDatabaseBox(self):
        deleteClassificationsButton = QPushButton("Remove all classifications")
        deleteClassificationsButton.clicked.connect(self.clearAllCalculatedPolarities)

        deleteEntitiesButton = QPushButton("Remove all entities")
        deleteEntitiesButton.clicked.connect(self.deleteAllEntities)

        deleteAssociationsButton = QPushButton("Remove all associations")
        deleteAssociationsButton.clicked.connect(self.deleteAllAssociations)

        layout = QVBoxLayout()
        layout.addWidget(deleteClassificationsButton)
        layout.addWidget(deleteAssociationsButton)
        layout.addWidget(deleteEntitiesButton)

        self.databaseBox = QGroupBox("Database")
        self.databaseBox.setLayout(layout)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def monthsBetweenDates(self, fromDate, toDate):
        curDate = QDate(fromDate)
        months =[]

        while curDate < toDate:
            months.append(curDate)
            curDate = curDate.addMonths(1)

        return months

    def makeMonthlyPolarityChart(self, entities, fromDate, toDate):
        cursor = mysql_conn.cursor()

        chartData = []

        for (entityId, entity) in entities:
            monthlyPol = self.selectAllPolaritiesForEntity(entityId, fromDate, toDate)

            trace0=Bar(
                x = [self.monthYearLabel(month) for (month, _, _) in monthlyPol],
                y = [(0.0 + rows.count(1L)) / (l+1) * 100 for (_, l, rows) in monthlyPol],
                name = entity,
                marker = Marker(
                        color = 'rgb(204,204,204)',
                        opacity = 0.5,
                ),
            )
            chartData.append(trace0)

        chartData = Data(chartData)
        layout = Layout( 
            xaxis=XAxis(
                #set x-axis' labels direction at 45 degree angle
                tickangle=-45,
                ),
            barmode='group',
        )
        fig = Figure(data = chartData, layout = layout)
        py.image.save_as({'data': chartData}, "polarities.png")
        img = Image.open("polarities.png")
        img.show()

    def makeMonthlyAppearanceChart(self, entities, fromDate, toDate):
        cursor = mysql_conn.cursor()

        chartData = []

        for (entityId, entity) in entities:
            monthlyApp = self.selectCountAssociationsForEntityBetweenDates(entityId, fromDate, toDate)

            trace0=Bar(
                x = [self.monthYearLabel(month) for (month, _) in monthlyApp],
                y = [count for (_, count) in monthlyApp],
                name = entity,
                marker = Marker(
                        color = 'rgb(204,204,204)',
                        opacity = 0.5,
                ),
            )
            chartData.append(trace0)

        chartData = Data(chartData)
        layout = Layout( 
            xaxis=XAxis(
                #set x-axis' labels direction at 45 degree angle
                tickangle=-45,
                ),
            barmode='group',
        )
        fig = Figure(data = chartData, layout = layout)
        py.image.save_as({'data': chartData}, "appearances.png")
        img = Image.open("appearances.png")
        img.show()

    def getStringDate(self, date):
        sDate = str(date.year())
        sDate += '-'+str(date.month())
        sDate += '-'+'01'
        time = '00:00:00'
        return sDate + ' ' + time

    def monthYearLabel(self, date):
        label = monthIntToString[date.month()] + ' '
        label += str(date.year())
        return label

    def createReport(self):
        reportType = self.reportTypeComboBox.currentText()
        fromDate = self.fromDateEdit.date()
        toDate = self.toDateEdit.date()
        entities = []

        if "All entities" in reportType:
            entities = self.selectAllEntities()
        else:
            selected = self.entityList.selectedItems()
            if len(selected) == 1:
                entity = selected[0].text()
                entities = [(self.selectEntityId(entity), entity)]

        if len(entities) > 0:
            if "Opinions" in reportType:
                self.makeMonthlyPolarityChart(entities, fromDate, toDate)
            else:
                print entities
                self.makeMonthlyAppearanceChart(entities, fromDate, toDate)

    def viewArticle(self):
        try:
            articleId = int(self.articleNumberLineEdit.text())
            if articleId > 0 and articleId < self.articleCount:
                self.viewArticleButton.setEnabled(False)
                self.articleNumberLineEdit.setDisabled(True)

                articleList = [i+1 for i in xrange(self.articleCount)]
                articleView = Article(articleId-1, articleList, parentW=self)
                articleView.exec_()

                self.viewArticleButton.setEnabled(True)
                self.articleNumberLineEdit.setDisabled(False)
        except ValueError:
            print "Invalid article id"

    def viewArticleByEntity(self):
        selected = self.entityList.selectedItems()

        if len(selected) == 1:
            articles = self.selectAllArticlesByEntity(selected[0].text())
            articleList = [a[0] for a in articles]
            articleView = Article(0, articleList, shuffle_=True, parentW=self)
            articleView.exec_()

    def addEntity(self):
        newEntity = self.addEntityLineEdit.text().strip()
        newEntity = re.sub(r' +', ' ', newEntity)
        cursor = mysql_conn.cursor()

        if len(newEntity) != 0:
            selectStmt = """SELECT *
                            FROM entities
                            WHERE entity=%s"""
            data = (newEntity,)
            cursor.execute(selectStmt, data)
            rows = cursor.fetchall()

            if len(rows) == 0:
                insertStmt = """INSERT INTO entities (entity)
                                VALUES (%s)"""
                data = (newEntity,)
                cursor.execute(insertStmt, data)
                cursor.execute("""COMMIT""")

                self.entityUpdate.emit()
                self.doAssociationsForEntity(newEntity)
                self.addEntityLineEdit.setText("")

    def removeEntity(self):
        selected = self.entityList.selectedItems()
        cursor = mysql_conn.cursor()

        for item in selected:
            self.deleteAssciationsForEntity(item.text())

            selectStmt = """SELECT entity_id
                            FROM entities
                            WHERE entity=%s"""
            data = (item.text(),)
            cursor.execute(selectStmt, data)
            entityId = cursor.fetchone()

            deleteStmt = """DELETE FROM entities
                            WHERE entity_id=%s"""
            data = (entityId[0],)
            cursor.execute(deleteStmt, data)
            cursor.execute("""COMMIT""")

            self.entityUpdate.emit()

    def updateEntityList(self):
        self.entityList.clear()
        entities = self.selectAllEntities()
        for entity in entities:
            self.entityList.addItem(entity[1])

        label = "Number of entities: " + str(len(entities))
        self.entitiesCountLabel.setText(label)

    def updateArticleInfo(self):
        self.articleCount = self.selectCountArticles()
        entityCount = self.selectCountEntities()
        associationsCount = self.selectCountAssociations()
        classifiedCount = self.selectCountClassifiedAssociations()

        label = "Number of articles: " + str(self.articleCount)
        self.articleCountLabel.setText(label)

        label = "Number of entities: " + str(entityCount)
        self.entitiesCountLabel.setText(label)

        label = "Number of classified associations: " + str(classifiedCount)
        self.classifiedCountLabel.setText(label)

        label = "Number of associations: " + str(associationsCount)
        self.associationsCountLabel.setText(label)

    def classifyAllAssociations(self):
        cursor = mysql_conn.cursor()

        entities = self.selectAllEntities()
        for (entityId, entity) in entities:
            manualPol = self.selectManualPolaritiesForEntity(entityId)
            trainingData = [self.selectArticle(id_)[4] for (id_, _) in manualPol]
            trainingTarget = [polarity for (_, polarity) in manualPol]

            algorithm = self.algorithmComboBox.currentText()
            textClf = Pipeline([('vect', CountVectorizer()),
                                ('tfidf', TfidfTransformer()),
                                ('clf', classifiers[algorithm]),
                                ])
            textClf.fit(trainingData, trainingTarget)

            # select all articles associated with entity that need to be classified
            selectStmt = """SELECT article_id
                            FROM assocEntityArticle
                            WHERE polarity_manual IS NULL
                            AND polarity_calculated IS NULL
                            AND entity_id=%s"""
            data = (entityId,)
            cursor.execute(selectStmt, data)
            ids = cursor.fetchall()

            if len(ids) > 0:
                ids = [a[0] for a in ids]
                testData = [self.selectArticle(id_)[4] for id_ in ids]

                predicted = textClf.predict(testData)
                print [x for x in predicted].count(1)
                updateData = zip(predicted, ids)
                updateData = [(polarity, entityId, id_) for (polarity, id_) in updateData]

                updateStmt = """UPDATE assocEntityArticle
                                SET polarity_calculated=%s
                                WHERE entity_id=%s AND article_id=%s"""
                cursor.executemany(updateStmt, updateData)
                cursor.execute("""COMMIT""")

                self.articleInfoUpdate.emit()

    def selectArticle(self, articleId):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT *
                        FROM articles
                        WHERE article_id=%s"""
        data = (articleId,)
        cursor.execute(selectStmt, data)
        row = cursor.fetchone()

        return row

    def selectEntityId(self, entity):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT entity_id
                FROM entities
                WHERE entity=%s"""
        data = (entity,)
        cursor.execute(selectStmt, data)
        entityId = cursor.fetchone()[0]

        return entityId

    def selectAllArticlesByEntity(self, entity):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT *
                        FROM articles
                        WHERE content LIKE %s"""
        data = ("%" + entity + "%",)
        cursor.execute(selectStmt, data)
        rows = cursor.fetchall()

        return rows

    def selectAllEntities(self):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT *
                        FROM entities"""
        cursor.execute(selectStmt)
        rows = cursor.fetchall()

        return rows

    def selectMinAndMaxDate(self):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT MIN(date), MAX(date)
                        FROM articles"""
        cursor.execute(selectStmt)
        row = cursor.fetchone()

        return row

    def selectCountArticles(self):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT count(*)
                        FROM articles"""
        cursor.execute(selectStmt)
        row = cursor.fetchone()

        return row[0]

    def selectCountAuthors(self):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT count(*)
                        FROM authors"""
        cursor.execute(selectStmt)
        row = cursor.fetchone()

        return row[0]

    def selectCountEntities(self):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT count(*)
                        FROM entities"""
        cursor.execute(selectStmt)
        row = cursor.fetchone()

        return row[0]

    def selectCountAssociations(self):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT count(*)
                        FROM assocEntityArticle"""
        cursor.execute(selectStmt)
        row = cursor.fetchone()

        return row[0]

    def selectCountAssociationsForEntityBetweenDates(self, entityId, fromDate, toDate):
        cursor = mysql_conn.cursor()
        months = self.monthsBetweenDates(fromDate, toDate)

        selectStmt = """SELECT count(*)
                        FROM assocEntityArticle a, articles b
                        WHERE a.article_id = b.article_id
                        AND b.date BETWEEN %s AND %s
                        AND a.entity_id=%s"""
        associations = []
        if len(months) != 0:
            for month in months:
                fromDateString = self.getStringDate(month)
                toDateString = self.getStringDate(month.addMonths(1))
                data = (fromDateString, toDateString, entityId)
                cursor.execute(selectStmt, data)
                count = cursor.fetchone()[0]
                associations.append((month, count))

        return associations

    def selectCountClassifiedAssociations(self):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT count(*)
                        FROM assocEntityArticle
                        WHERE polarity_calculated IS NOT NULL
                        OR polarity_manual IS NOT NULL"""
        cursor.execute(selectStmt)
        row = cursor.fetchone()

        return row[0]

    def selectManualPolaritiesForEntity(self, entityId):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT article_id, polarity_manual
                        FROM assocEntityArticle
                        WHERE polarity_manual IS NOT NULL
                        AND entity_id=%s"""
        data = (entityId,)
        cursor.execute(selectStmt, data)
        rows = cursor.fetchall()

        return rows

    def selectAllPolaritiesForEntity(self, entityId, fromDate, toDate):
        cursor = mysql_conn.cursor()
        months = self.monthsBetweenDates(fromDate, toDate)

        selectStmt = """SELECT a.polarity_manual, a.polarity_calculated
                        FROM assocEntityArticle a, articles b
                        WHERE (a.polarity_manual IS NOT NULL
                            OR a.polarity_calculated IS NOT NULL)
                        AND a.article_id = b.article_id
                        AND b.date BETWEEN %s AND %s
                        AND a.entity_id=%s"""

        polarities = []
        if len(months) != 0:
            for month in months:
                fromDateString = self.getStringDate(month)
                toDateString = self.getStringDate(month.addMonths(1))
                data = (fromDateString, toDateString, entityId)
                cursor.execute(selectStmt, data)
                rows = cursor.fetchall()
                rows = [a or b for a, b in rows]
                polarities.append((month, len(rows), rows))

        return polarities

    def doAssociationsForEntity(self, entity):
        cursor = mysql_conn.cursor()

        # select entity_id for entity given as parameter
        entityId = self.selectEntityId(entity)

        # select list of article_id for which associations exist
        # in database for entity given as param
        selectStmt = """SELECT article_id
                        FROM assocEntityArticle
                        WHERE entity_id=%s"""
        data = (entityId,)
        cursor.execute(selectStmt, data)
        articleIdsInDB = cursor.fetchall()
        articleIdsInDB = [pair[0] for pair in articleIdsInDB]

        # select all articles that contain entity in content
        selectStmt = """SELECT article_id
                        FROM articles
                        WHERE content LIKE %s"""
        data = ("%" + entity + "%",)
        cursor.execute(selectStmt, data)
        rows = cursor.fetchall()
        rows = [pair[0] for pair in rows]

        # find articles for which associations don't exist in the database
        diff = list(set(rows) - set(articleIdsInDB))
        if len(diff) != 0:
            insertStmt = """INSERT INTO assocEntityArticle (article_id, entity_id)
                            VALUES (%s, %s)"""
            data = [(articleId, entityId) for articleId in diff]
            cursor.executemany(insertStmt, data)
            cursor.execute("""COMMIT""")

            self.articleInfoUpdate.emit()

    def deleteAssciationsForEntity(self, entity):
        cursor = mysql_conn.cursor()

        selectStmt = """SELECT entity_id
                        FROM entities
                        WHERE entity=%s"""
        data = (entity,)
        cursor.execute(selectStmt, data)
        entityId = cursor.fetchone()[0]

        deleteStmt = """DELETE FROM assocEntityArticle
                        WHERE entity_id=%s"""
        data = (entityId,)
        cursor.execute(deleteStmt, data)
        cursor.execute("""COMMIT""")

        self.articleInfoUpdate.emit()

    def doAllAssociations(self):
        cursor = mysql_conn.cursor()

        entities = self.selectAllEntities()
        for entity in entities:
            self.doAssociationsForEntity(entity)

        self.articleInfoUpdate.emit()

    def deleteAllAssociations(self):
        cursor = mysql_conn.cursor()

        deleteStmt = """DELETE FROM assocEntityArticle
                        WHERE article_id > 0"""
        cursor.execute(deleteStmt)
        cursor.execute("""COMMIT""")

        self.articleInfoUpdate.emit()

    def clearAllCalculatedPolarities(self):
        cursor = mysql_conn.cursor()

        updateStmt = """UPDATE assocEntityArticle
                        SET polarity_calculated=%s
                        WHERE polarity_calculated IS NOT NULL"""
        data = (None,)
        cursor.execute(updateStmt, data)
        cursor.execute("""COMMIT""")

        self.articleInfoUpdate.emit()

    def deleteAllArticles(self):
        try:
            cursor = mysql_conn.cursor()

            deleteStmt = """DELETE FROM articles
                            WHERE article_id > 0"""
            cursor.execute(deleteStmt)
            alterTableStmt = """ALTER TABLE articles AUTO_INCREMENT = 1"""
            cursor.execute(alterTableStmt)
            cursor.execute("""COMMIT""")

            self.articleInfoUpdate.emit()
        except IntegrityError:
            pass

    def deleteAllAuthors(self):
        cursor = mysql_conn.cursor()

        deleteStmt = """DELETE FROM authors
                        WHERE author_id > 0"""
        cursor.execute(deleteStmt)
        alterTableStmt = """ALTER TABLE authors AUTO_INCREMENT = 1"""
        cursor.execute(alterTableStmt)
        cursor.execute("""COMMIT""")

    def deleteAllArticlesAndAuthors(self):
        self.deleteAllArticles()
        self.deleteAllAuthors()

    def deleteAllEntities(self):
        cursor = mysql_conn.cursor()

        deleteStmt = """DELETE FROM entities
                        WHERE entity_id > 0"""
        cursor.execute(deleteStmt)
        alterTableStmt = """ALTER TABLE entities AUTO_INCREMENT = 1"""
        cursor.execute(alterTableStmt)
        cursor.execute("""COMMIT""")

        self.articleInfoUpdate.emit()
        self.entityUpdate.emit()
Ejemplo n.º 39
0
    def setupUi(self):
        self.setObjectName("MainWindow")
        self.setFixedSize(1040, 915)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        icon = QIcon()
        icon.addPixmap(QPixmap('./resource/weather-thunder.png'),QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.centralwidget = QWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
        self.centralwidget.setSizePolicy(sizePolicy)
        self.centralwidget.setObjectName("centralwidget")
        self.layoutWidget = QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QRect(32, 10, 979, 851))
        self.layoutWidget.setObjectName("layoutWidget")
        self.verticalLayout_5 =QVBoxLayout(self.layoutWidget)
        self.verticalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.datetime_label = QLabel(self.layoutWidget)
        self.datetime_label.setObjectName("datetime_label")
        self.horizontalLayout.addWidget(self.datetime_label)
        self.datetime = QDateEdit(self.layoutWidget)
        self.datetime.setDateTime(QDateTime(QDate(self.lastyear, 1, 1), QTime(0, 0, 0)))
        self.datetime.setObjectName("datetime")
        self.horizontalLayout.addWidget(self.datetime)
        spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem1)
        self.target_area_label = QLabel(self.layoutWidget)
        self.target_area_label.setObjectName("target_area_label")
        self.horizontalLayout.addWidget(self.target_area_label)
        self.target_area = QComboBox(self.layoutWidget)
        self.target_area.setObjectName("target_area")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.target_area.addItem("")
        self.horizontalLayout.addWidget(self.target_area)
        spacerItem2 = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.verticalLayout_5.addLayout(self.horizontalLayout)
        self.tabWidget = QTabWidget(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
        self.tabWidget.setSizePolicy(sizePolicy)
        self.tabWidget.setObjectName("tabWidget")
        self.density_tab = QWidget()
        self.density_tab.setObjectName("density_tab")
        self.verticalLayout_3 =QVBoxLayout(self.density_tab)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.verticalLayout_2 =QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_2 = QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.density_cell_label = QLabel(self.density_tab)
        self.density_cell_label.setObjectName("density_cell_label")
        self.horizontalLayout_2.addWidget(self.density_cell_label)
        self.density_cell = QSpinBox(self.density_tab)
        self.density_cell.setProperty("value", 10)
        self.density_cell.setObjectName("density_cell")
        self.horizontalLayout_2.addWidget(self.density_cell)
        spacerItem3 = QSpacerItem(40, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem3)
        self.density_class_label = QLabel(self.density_tab)
        self.density_class_label.setObjectName("density_class_label")
        self.horizontalLayout_2.addWidget(self.density_class_label)
        self.density_class = QSpinBox(self.density_tab)
        self.density_class.setProperty("value", 10)
        self.density_class.setObjectName("density_class")
        self.horizontalLayout_2.addWidget(self.density_class)
        spacerItem4 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem4)
        self.density_mxd = QPushButton(self.density_tab)
        self.density_mxd.setObjectName("density_mxd")
        self.horizontalLayout_2.addWidget(self.density_mxd)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.density_view = QGraphicsView(self.density_tab)
        self.density_view.setObjectName("density_view")
        self.verticalLayout_2.addWidget(self.density_view)
        self.verticalLayout_3.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.density_tab, "")
        self.day_tab = QWidget()
        self.day_tab.setObjectName("day_tab")
        self.verticalLayout_4 =QVBoxLayout(self.day_tab)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.verticalLayout =QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_3 =QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.day_cell_label = QLabel(self.day_tab)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.day_cell_label.sizePolicy().hasHeightForWidth())
        self.day_cell_label.setSizePolicy(sizePolicy)
        self.day_cell_label.setObjectName("day_cell_label")
        self.horizontalLayout_3.addWidget(self.day_cell_label)
        self.day_cell = QSpinBox(self.day_tab)
        self.day_cell.setProperty("value", 15)
        self.day_cell.setObjectName("day_cell")
        self.horizontalLayout_3.addWidget(self.day_cell)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem5)
        self.day_class_label = QLabel(self.day_tab)
        self.day_class_label.setObjectName("day_class_label")
        self.horizontalLayout_3.addWidget(self.day_class_label)
        self.day_class = QSpinBox(self.day_tab)
        self.day_class.setProperty("value", 10)
        self.day_class.setObjectName("day_class")
        self.horizontalLayout_3.addWidget(self.day_class)
        spacerItem6 = QSpacerItem(478, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem6)
        self.day_mxd = QPushButton(self.day_tab)
        self.day_mxd.setObjectName("day_mxd")
        self.horizontalLayout_3.addWidget(self.day_mxd)
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.day_view = QGraphicsView(self.day_tab)
        self.day_view.setObjectName("day_view")
        self.verticalLayout.addWidget(self.day_view)
        self.verticalLayout_4.addLayout(self.verticalLayout)
        self.tabWidget.addTab(self.day_tab, "")
        self.verticalLayout_5.addWidget(self.tabWidget)
        self.horizontalLayout_4 =QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.progressBar = QProgressBar(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth())
        self.progressBar.setSizePolicy(sizePolicy)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout_4.addWidget(self.progressBar)
        self.execute_button = QPushButton(self.layoutWidget)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.execute_button.sizePolicy().hasHeightForWidth())
        self.execute_button.setSizePolicy(sizePolicy)
        self.execute_button.setObjectName("execute_button")
        self.horizontalLayout_4.addWidget(self.execute_button)
        self.verticalLayout_5.addLayout(self.horizontalLayout_4)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 1040, 26))
        self.menubar.setObjectName("menubar")
        self.file_menu = QMenu(self.menubar)
        self.file_menu.setObjectName("file_menu")
        self.help_menu = QMenu(self.menubar)
        self.help_menu.setObjectName("help_menu")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)
        self.action_add_data = QAction(self)
        self.action_add_data.setObjectName("action_add_data")
        self.action_help = QAction(self)
        self.action_help.setObjectName("action_help")
        self.action_about = QAction(self)
        self.action_about.setObjectName("action_about")
        self.action_save_pic = QAction(self)
        self.action_save_pic.setObjectName("action_save_pic")
        self.file_menu.addAction(self.action_add_data)
        self.file_menu.addAction(self.action_save_pic)
        self.help_menu.addAction(self.action_help)
        self.help_menu.addAction(self.action_about)
        self.menubar.addAction(self.file_menu.menuAction())
        self.menubar.addAction(self.help_menu.menuAction())

        self.retranslateUi()
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(self)
        self.center()
        self.show()

        self.target_area.activated[str].connect(self.updateTargetArea)
        self.datetime.dateChanged.connect(self.updateDatetime)
        self.density_cell.valueChanged.connect(self.updateDensityCell)
        self.density_class.valueChanged.connect(self.updateDensityClass)
        self.day_cell.valueChanged.connect(self.updateDayCell)
        self.day_class.valueChanged.connect(self.updateDayClass)

        self.action_add_data.triggered.connect(self.addData)
        self.action_save_pic.triggered.connect(self.savePic)
        self.action_about.triggered.connect(self.showAbout)
        self.action_help.triggered.connect(self.showHelp)
        self.execute_button.clicked.connect(self.execute)
        self.density_mxd.clicked.connect(self.openMxdDensity)
        self.day_mxd.clicked.connect(self.openMxdDay)


        self.density_mxd.setDisabled(True)
        self.day_mxd.setDisabled(True)
        self.action_save_pic.setDisabled(True)
Ejemplo n.º 40
0
	def initUI(self):
		main_layout = QVBoxLayout()

		f_web = QGroupBox("From the Web")
		f_web.setCheckable(False)
		main_layout.addWidget(f_web)
		web_layout = QHBoxLayout()
		f_web.setLayout(web_layout)

		f_local = QGroupBox("From local folder")
		f_local.setCheckable(False)
		main_layout.addWidget(f_local)
		local_layout = QHBoxLayout()
		f_local.setLayout(local_layout)

		f_series = QGroupBox("Series Info")
		f_series.setCheckable(False)
		main_layout.addWidget(f_series)
		series_layout = QFormLayout()
		f_series.setLayout(series_layout)

		def basic_web(name):
			return QLabel(name), QLineEdit(), QPushButton("Fetch")

		exh_lbl, exh_edit, exh_btn = basic_web("ExHentai:")
		web_layout.addWidget(exh_lbl, 0, Qt.AlignLeft)
		web_layout.addWidget(exh_edit, 0)
		web_layout.addWidget(exh_btn, 0, Qt.AlignRight)

		choose_folder = QPushButton("Choose Folder")
		choose_folder.clicked.connect(self.choose_dir)
		local_layout.addWidget(choose_folder, Qt.AlignLeft)

		self.title_edit = QLineEdit()
		self.title_edit.setFocus()
		self.author_edit = QLineEdit()
		self.descr_edit = QTextEdit()
		self.descr_edit.setFixedHeight(70)
		self.descr_edit.setPlaceholderText("HTML 4 tags are supported")
		self.lang_box = QComboBox()
		self.lang_box.addItems(["English", "Japanese", "Other"])
		self.lang_box.setCurrentIndex(0)
		self.tags_edit = QLineEdit()
		self.tags_edit.setPlaceholderText("namespace1:tag1, tag2, namespace3:tag3, etc..")
		self.type_box = QComboBox()
		self.type_box.addItems(["Manga", "Doujinshi", "Other"])
		self.type_box.setCurrentIndex(0)
		#self.type_box.currentIndexChanged[int].connect(self.doujin_show)
		#self.doujin_parent = QLineEdit()
		#self.doujin_parent.setVisible(False)
		self.status_box = QComboBox()
		self.status_box.addItems(["Unknown", "Ongoing", "Completed"])
		self.status_box.setCurrentIndex(0)
		self.pub_edit = QDateEdit()
		self.pub_edit.setCalendarPopup(True)
		self.pub_edit.setDate(QDate.currentDate())
		self.path_lbl = QLabel("unspecified...")
		self.path_lbl.setWordWrap(True)

		series_layout.addRow("Title:", self.title_edit)
		series_layout.addRow("Author:", self.author_edit)
		series_layout.addRow("Description:", self.descr_edit)
		series_layout.addRow("Language:", self.lang_box)
		series_layout.addRow("Tags:", self.tags_edit)
		series_layout.addRow("Type:", self.type_box)
		series_layout.addRow("Publication Date:", self.pub_edit)
		series_layout.addRow("Path:", self.path_lbl)

		final_buttons = QHBoxLayout()
		final_buttons.setAlignment(Qt.AlignRight)
		main_layout.addLayout(final_buttons)
		done = QPushButton("Done")
		done.setDefault(True)
		done.clicked.connect(self.accept)
		cancel = QPushButton("Cancel")
		cancel.clicked.connect(self.reject)
		final_buttons.addWidget(cancel)
		final_buttons.addWidget(done)


		self.setLayout(main_layout)
Ejemplo n.º 41
0
    def __init_scalesTabWidget__(self):

        class QRowLayout(QGridLayout):
            def __init__(self, items, parent=None):
                super(QRowLayout, self).__init__(parent)

                for col, item in enumerate(items):
                    self.addWidget(item, 0, col)

                self.setContentsMargins(0, 0, 0, 0)
                self.setColumnStretch(0, 100)

        # ---- Time axis properties

        # Generate the widgets :

        self.date_start_widget = QDateEdit()
        self.date_start_widget.setDisplayFormat('01 / MM / yyyy')
        self.date_start_widget.setAlignment(Qt.AlignCenter)
        self.date_start_widget.dateChanged.connect(self.layout_changed)

        self.date_end_widget = QDateEdit()
        self.date_end_widget.setDisplayFormat('01 / MM / yyyy')
        self.date_end_widget.setAlignment(Qt.AlignCenter)
        self.date_end_widget.dateChanged.connect(self.layout_changed)

        self.time_scale_label = QComboBox()
        self.time_scale_label.setEditable(False)
        self.time_scale_label.setInsertPolicy(QComboBox.NoInsert)
        self.time_scale_label.addItems(['Month', 'Year'])
        self.time_scale_label.setCurrentIndex(0)
        self.time_scale_label.currentIndexChanged.connect(self.layout_changed)

        self.dateDispFreq_spinBox = QSpinBox()
        self.dateDispFreq_spinBox.setSingleStep(1)
        self.dateDispFreq_spinBox.setMinimum(1)
        self.dateDispFreq_spinBox.setMaximum(100)
        self.dateDispFreq_spinBox.setValue(
            self.hydrograph.date_labels_pattern)
        self.dateDispFreq_spinBox.setAlignment(Qt.AlignCenter)
        self.dateDispFreq_spinBox.setKeyboardTracking(False)
        self.dateDispFreq_spinBox.valueChanged.connect(self.layout_changed)

        # Setting up the layout :

        widget_time_scale = QFrame()
        widget_time_scale.setFrameStyle(0)
        grid_time_scale = QGridLayout()

        GRID = [[QLabel('From :'), self.date_start_widget],
                [QLabel('To :'), self.date_end_widget],
                [QLabel('Scale :'), self.time_scale_label],
                [QLabel('Date Disp. Pattern:'),
                 self.dateDispFreq_spinBox]]

        for i, ROW in enumerate(GRID):
            grid_time_scale.addLayout(QRowLayout(ROW), i, 1)

        grid_time_scale.setVerticalSpacing(5)
        grid_time_scale.setContentsMargins(10, 10, 10, 10)

        widget_time_scale.setLayout(grid_time_scale)

        # ----- Water level axis properties

        # Widget :

        self.waterlvl_scale = QDoubleSpinBox()
        self.waterlvl_scale.setSingleStep(0.05)
        self.waterlvl_scale.setMinimum(0.05)
        self.waterlvl_scale.setSuffix('  m')
        self.waterlvl_scale.setAlignment(Qt.AlignCenter)
        self.waterlvl_scale.setKeyboardTracking(False)
        self.waterlvl_scale.valueChanged.connect(self.layout_changed)
        self.waterlvl_scale.setFixedWidth(100)

        self.waterlvl_max = QDoubleSpinBox()
        self.waterlvl_max.setSingleStep(0.1)
        self.waterlvl_max.setSuffix('  m')
        self.waterlvl_max.setAlignment(Qt.AlignCenter)
        self.waterlvl_max.setMinimum(-1000)
        self.waterlvl_max.setMaximum(1000)
        self.waterlvl_max.setKeyboardTracking(False)
        self.waterlvl_max.valueChanged.connect(self.layout_changed)
        self.waterlvl_max.setFixedWidth(100)

        self.NZGridWL_spinBox = QSpinBox()
        self.NZGridWL_spinBox.setSingleStep(1)
        self.NZGridWL_spinBox.setMinimum(1)
        self.NZGridWL_spinBox.setMaximum(50)
        self.NZGridWL_spinBox.setValue(self.hydrograph.NZGrid)
        self.NZGridWL_spinBox.setAlignment(Qt.AlignCenter)
        self.NZGridWL_spinBox.setKeyboardTracking(False)
        self.NZGridWL_spinBox.valueChanged.connect(self.layout_changed)
        self.NZGridWL_spinBox.setFixedWidth(100)

        self.datum_widget = QComboBox()
        self.datum_widget.addItems(['Ground Surface', 'Sea Level'])
        self.datum_widget.currentIndexChanged.connect(self.layout_changed)

        # Layout :

        subgrid_WLScale = QGridLayout()

        GRID = [[QLabel('Minimum :'), self.waterlvl_max],
                [QLabel('Scale :'), self.waterlvl_scale],
                [QLabel('Grid Divisions :'), self.NZGridWL_spinBox],
                [QLabel('Datum :'), self.datum_widget]]

        for i, ROW in enumerate(GRID):
            subgrid_WLScale.addLayout(QRowLayout(ROW), i, 1)

        subgrid_WLScale.setVerticalSpacing(5)
        subgrid_WLScale.setContentsMargins(10, 10, 10, 10)  # (L, T, R, B)

        WLScale_widget = QFrame()
        WLScale_widget.setFrameStyle(0)
        WLScale_widget.setLayout(subgrid_WLScale)

        # ---- Weather Axis

        # Widgets :

        self.Ptot_scale = QSpinBox()
        self.Ptot_scale.setSingleStep(5)
        self.Ptot_scale.setMinimum(5)
        self.Ptot_scale.setMaximum(500)
        self.Ptot_scale.setValue(20)
        self.Ptot_scale.setSuffix('  mm')
        self.Ptot_scale.setAlignment(Qt.AlignCenter)

        self.qweather_bin = QComboBox()
        self.qweather_bin.setEditable(False)
        self.qweather_bin.setInsertPolicy(QComboBox.NoInsert)
        self.qweather_bin.addItems(['day', 'week', 'month'])
        self.qweather_bin.setCurrentIndex(1)

        # Layout :

        layout = QGridLayout()

        GRID = [[QLabel('Precip. Scale :'), self.Ptot_scale],
                [QLabel('Resampling :'), self.qweather_bin]]

        for i, row in enumerate(GRID):
            layout.addLayout(QRowLayout(row), i, 1)

        layout.setVerticalSpacing(5)
        layout.setContentsMargins(10, 10, 10, 10)  # (L,T,R,B)
        layout.setRowStretch(i+1, 100)

        widget_weather_scale = QFrame()
        widget_weather_scale.setFrameStyle(0)
        widget_weather_scale.setLayout(layout)

        # ---- ASSEMBLING TABS

        tabscales = QTabWidget()
        tabscales.addTab(widget_time_scale, 'Time')
        tabscales.addTab(WLScale_widget, 'Water Level')
        tabscales.addTab(widget_weather_scale, 'Weather')

        return tabscales
Ejemplo n.º 42
0
	def commonUI(self):
		f_web = QGroupBox("Metadata from the Web")
		f_web.setCheckable(False)
		self.main_layout.addWidget(f_web)
		web_main_layout = QVBoxLayout()
		web_layout = QHBoxLayout()
		web_main_layout.addLayout(web_layout)
		f_web.setLayout(web_main_layout)

		f_gallery = QGroupBox("Gallery Info")
		f_gallery.setCheckable(False)
		self.main_layout.addWidget(f_gallery)
		gallery_layout = QFormLayout()
		f_gallery.setLayout(gallery_layout)

		def basic_web(name):
			return QLabel(name), QLineEdit(), QPushButton("Get metadata"), QProgressBar()

		url_lbl, self.url_edit, url_btn, url_prog = basic_web("URL:")
		url_btn.clicked.connect(lambda: self.web_metadata(self.url_edit.text(), url_btn,
											url_prog))
		url_prog.setTextVisible(False)
		url_prog.setMinimum(0)
		url_prog.setMaximum(0)
		web_layout.addWidget(url_lbl, 0, Qt.AlignLeft)
		web_layout.addWidget(self.url_edit, 0)
		web_layout.addWidget(url_btn, 0, Qt.AlignRight)
		web_layout.addWidget(url_prog, 0, Qt.AlignRight)
		self.url_edit.setPlaceholderText("Paste g.e-hentai/exhentai gallery url or just press the button.")
		url_prog.hide()

		self.title_edit = QLineEdit()
		self.author_edit = QLineEdit()
		author_completer = misc.GCompleter(self, False, True, False)
		author_completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.author_edit.setCompleter(author_completer)
		self.descr_edit = QTextEdit()
		self.descr_edit.setFixedHeight(45)
		self.descr_edit.setAcceptRichText(True)
		self.lang_box = QComboBox()
		self.lang_box.addItems(["English", "Japanese", "Other"])
		self.lang_box.setCurrentIndex(0)
		tags_l = QVBoxLayout()
		tag_info = misc.ClickedLabel("How do i write namespace & tags? (hover)", parent=self)
		tag_info.setToolTip("Ways to write tags:\n\nNormal tags:\ntag1, tag2, tag3\n\n"+
					  "Namespaced tags:\nns1:tag1, ns1:tag2\n\nNamespaced tags with one or more"+
					  " tags under same namespace:\nns1:[tag1, tag2, tag3], ns2:[tag1, tag2]\n\n"+
					  "Those three ways of writing namespace & tags can be combined freely.\n"+
					  "Tags are seperated by a comma, NOT whitespace.\nNamespaces will be capitalized while tags"+
					  " will be lowercased.")
		tag_info.setToolTipDuration(99999999)
		tags_l.addWidget(tag_info)
		self.tags_edit = misc.CompleterTextEdit()
		self.tags_edit.setCompleter(misc.GCompleter(self, False, False))
		tags_l.addWidget(self.tags_edit, 3)
		self.tags_edit.setFixedHeight(70)
		self.tags_edit.setPlaceholderText("Press Tab to autocomplete (Ctrl + E to show popup)")
		self.type_box = QComboBox()
		self.type_box.addItems(["Manga", "Doujinshi", "Artist CG Sets", "Game CG Sets",
						  "Western", "Image Sets", "Non-H", "Cosplay", "Other"])
		self.type_box.setCurrentIndex(0)
		#self.type_box.currentIndexChanged[int].connect(self.doujin_show)
		#self.doujin_parent = QLineEdit()
		#self.doujin_parent.setVisible(False)
		self.status_box = QComboBox()
		self.status_box.addItems(["Unknown", "Ongoing", "Completed"])
		self.status_box.setCurrentIndex(0)
		self.pub_edit = QDateEdit()
		self.pub_edit.setCalendarPopup(True)
		self.pub_edit.setDate(QDate.currentDate())
		self.path_lbl = QLabel("")
		self.path_lbl.setWordWrap(True)

		link_layout = QHBoxLayout()
		self.link_lbl = QLabel("")
		self.link_lbl.setWordWrap(True)
		self.link_edit = QLineEdit()
		link_layout.addWidget(self.link_edit)
		link_layout.addWidget(self.link_lbl)
		self.link_edit.hide()
		self.link_btn = QPushButton("Modify")
		self.link_btn.setFixedWidth(50)
		self.link_btn2 = QPushButton("Set")
		self.link_btn2.setFixedWidth(40)
		self.link_btn.clicked.connect(self.link_modify)
		self.link_btn2.clicked.connect(self.link_set)
		link_layout.addWidget(self.link_btn)
		link_layout.addWidget(self.link_btn2)
		self.link_btn2.hide()

		gallery_layout.addRow("Title:", self.title_edit)
		gallery_layout.addRow("Author:", self.author_edit)
		gallery_layout.addRow("Description:", self.descr_edit)
		gallery_layout.addRow("Language:", self.lang_box)
		gallery_layout.addRow("Tags:", tags_l)
		gallery_layout.addRow("Type:", self.type_box)
		gallery_layout.addRow("Status:", self.status_box)
		gallery_layout.addRow("Publication Date:", self.pub_edit)
		gallery_layout.addRow("Path:", self.path_lbl)
		gallery_layout.addRow("Link:", link_layout)

		self.title_edit.setFocus()
    def createEditor(self, parent, option, index):
        editor = QDateEdit(parent=parent)

        editor.setMinimumDate(datetime.datetime(year=2017, month=9, day=1))
        editor.setMaximumDate(datetime.datetime(year=2020, month=9, day=1))
        editor.setDisplayFormat("yyyy-MM-dd")
        editor.setCalendarPopup(True)

        # setFrame(): tell whether the line edit draws itself with a frame.
        # If enabled (the default) the line edit draws itself inside a frame, otherwise the line edit draws itself without any frame.
        editor.setFrame(False)

        return editor
Ejemplo n.º 44
0
class TaskView(QWidget):
    close = pyqtSignal()

    def __init__(self, model):
        super().__init__()
        self.header = QLabel('')
        self.desc = QLineEdit()
        self.date = QDateEdit()
        self.time = QTimeEdit()
        self.init_ui()

        self.mapper = QDataWidgetMapper()
        self.mapper.setModel(model)
        self.mapper.setSubmitPolicy(QDataWidgetMapper.ManualSubmit)
        self.mapper.addMapping(self.desc, TaskModel.col_desc)
        self.mapper.addMapping(self.date, TaskModel.col_date)
        self.mapper.addMapping(self.time, TaskModel.col_time)

    def set_task(self, index):
        self.mapper.setCurrentIndex(index)
        self.header.setText('РЕДАКТИРОВАНИЕ ЗАДАЧИ')
        # text = 'НОВАЯ ЗАДАЧА'
        # self.date.setDate(QDate().currentDate())

    def create_date(self):
        self.date.setDisplayFormat('dd.MM.yyyy')
        self.date.setCalendarPopup(True)
        self.date.setFixedWidth(120)

        return self.date

    def create_time(self):
        self.time.setDisplayFormat('hh.mm')
        self.time.setFixedWidth(120)

        return self.time

    def create_date_buttons(self):
        date_lt = QHBoxLayout()

        btn_now = QPushButton('сегодня')
        btn_now.clicked.connect(lambda: self.date.setDate(QDate().currentDate()))
        date_lt.addWidget(btn_now, 0, Qt.AlignCenter)

        btn_tomorrow = QPushButton('завтра')
        btn_tomorrow.clicked.connect(lambda: self.date.setDate(QDate().currentDate().addDays(1)))
        date_lt.addWidget(btn_tomorrow, 0, Qt.AlignCenter)

        btn_week_later = QPushButton('через неделю')
        btn_week_later.clicked.connect(lambda: self.date.setDate(QDate().currentDate().addDays(7)))
        date_lt.addWidget(btn_week_later, 0, Qt.AlignCenter)

        return date_lt

    # def create_time_choice(self):
    #     self.time.setMaxVisibleItems(15)
    #     self.time.setStyleSheet('QComboBox { combobox-popup: 0; }')
    #     for it in range(24):
    #         self.time.insertItem(it * 2 + 0, '%.2d:00' % it)
    #         self.time.insertItem(it * 2 + 1, '%.2d:30' % it)
    #
    #     return self.time

    def save(self):
        print('save', self.mapper.submit())
        self.close.emit()

    def cancel(self):
        self.close.emit()

    def remove(self):
        self.mapper.model().removeRow(self.mapper.currentIndex())
        self.close.emit()

    def create_control_buttons(self):
        control_lt = QHBoxLayout()

        btn_save = QPushButton('Сохранить')
        btn_save.clicked.connect(self.save)
        control_lt.addWidget(btn_save, 0, Qt.AlignCenter)

        btn_cancel = QPushButton('Отменить')
        btn_cancel.clicked.connect(self.cancel)
        control_lt.addWidget(btn_cancel, 0, Qt.AlignCenter)

        btn_remove = QPushButton('Удалить')
        btn_remove.clicked.connect(self.remove)
        control_lt.addWidget(btn_remove, 1, Qt.AlignRight)

        return control_lt

    def create_main_form(self):
        fm = QFormLayout()

        fm.addRow(self.header)
        fm.addRow(QLabel(''))

        fm.addRow(self.desc)
        fm.addRow(QLabel(''))

        fm.addRow(QLabel('Когда это нужно сделать?'))
        fm.addRow(self.create_date())
        fm.addRow(self.create_date_buttons())
        fm.addRow(QLabel(''))

        fm.addRow(QLabel('Во сколько?'))
        fm.addRow(self.create_time())

        return fm

    def init_ui(self):
        layout = QVBoxLayout()
        layout.addLayout(self.create_main_form())
        layout.addStretch()
        layout.addLayout(self.create_control_buttons())
        self.setLayout(layout)
Ejemplo n.º 45
0
class GalleryDialog(QWidget):
	"""
	A window for adding/modifying gallery.
	Pass a list of QModelIndexes to edit their data
	or pass a path to preset path
	"""

	gallery_queue = queue.Queue()
	SERIES = pyqtSignal(list)
	SERIES_EDIT = pyqtSignal(list, int)
	#gallery_list = [] # might want to extend this to allow mass gallery adding

	def __init__(self, parent=None, arg=None):
		super().__init__(parent, Qt.Dialog)
		self.setAttribute(Qt.WA_DeleteOnClose)
		self.parent_widget = parent
		log_d('Triggered Gallery Edit/Add Dialog')
		m_l = QVBoxLayout()
		self.main_layout = QVBoxLayout()
		dummy = QWidget(self)
		scroll_area = QScrollArea(self)
		scroll_area.setWidgetResizable(True)
		scroll_area.setFrameStyle(scroll_area.StyledPanel)
		dummy.setLayout(self.main_layout)
		scroll_area.setWidget(dummy)
		m_l.addWidget(scroll_area, 3)

		final_buttons = QHBoxLayout()
		final_buttons.setAlignment(Qt.AlignRight)
		m_l.addLayout(final_buttons)
		self.done = QPushButton("Done")
		self.done.setDefault(True)
		cancel = QPushButton("Cancel")
		final_buttons.addWidget(cancel)
		final_buttons.addWidget(self.done)

		def new_gallery():
			self.setWindowTitle('Add a new gallery')
			self.newUI()
			self.commonUI()
			self.done.clicked.connect(self.accept)
			cancel.clicked.connect(self.reject)

		if arg:
			if isinstance(arg, list):
				self.setWindowTitle('Edit gallery')
				self.position = arg[0].row()
				for index in arg:
					gallery = index.data(Qt.UserRole+1)
					self.commonUI()
					self.setGallery(gallery)
				self.done.clicked.connect(self.accept_edit)
				cancel.clicked.connect(self.reject_edit)
			elif isinstance(arg, str):
				new_gallery()
				self.choose_dir(arg)
		else:
			new_gallery()

		log_d('GalleryDialog: Create UI: successful')
		#TODO: Implement a way to mass add galleries
		#IDEA: Extend dialog in a ScrollArea with more forms...

		self.setLayout(m_l)
		self.resize(500,560)
		frect = self.frameGeometry()
		frect.moveCenter(QDesktopWidget().availableGeometry().center())
		self.move(frect.topLeft())
		#self.setAttribute(Qt.WA_DeleteOnClose)

	def commonUI(self):
		f_web = QGroupBox("Metadata from the Web")
		f_web.setCheckable(False)
		self.main_layout.addWidget(f_web)
		web_main_layout = QVBoxLayout()
		web_layout = QHBoxLayout()
		web_main_layout.addLayout(web_layout)
		f_web.setLayout(web_main_layout)

		f_gallery = QGroupBox("Gallery Info")
		f_gallery.setCheckable(False)
		self.main_layout.addWidget(f_gallery)
		gallery_layout = QFormLayout()
		f_gallery.setLayout(gallery_layout)

		def basic_web(name):
			return QLabel(name), QLineEdit(), QPushButton("Get metadata"), QProgressBar()

		url_lbl, self.url_edit, url_btn, url_prog = basic_web("URL:")
		url_btn.clicked.connect(lambda: self.web_metadata(self.url_edit.text(), url_btn,
											url_prog))
		url_prog.setTextVisible(False)
		url_prog.setMinimum(0)
		url_prog.setMaximum(0)
		web_layout.addWidget(url_lbl, 0, Qt.AlignLeft)
		web_layout.addWidget(self.url_edit, 0)
		web_layout.addWidget(url_btn, 0, Qt.AlignRight)
		web_layout.addWidget(url_prog, 0, Qt.AlignRight)
		self.url_edit.setPlaceholderText("Paste g.e-hentai/exhentai gallery url or just press the button.")
		url_prog.hide()

		self.title_edit = QLineEdit()
		self.author_edit = QLineEdit()
		author_completer = misc.GCompleter(self, False, True, False)
		author_completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.author_edit.setCompleter(author_completer)
		self.descr_edit = QTextEdit()
		self.descr_edit.setFixedHeight(45)
		self.descr_edit.setAcceptRichText(True)
		self.lang_box = QComboBox()
		self.lang_box.addItems(["English", "Japanese", "Other"])
		self.lang_box.setCurrentIndex(0)
		tags_l = QVBoxLayout()
		tag_info = misc.ClickedLabel("How do i write namespace & tags? (hover)", parent=self)
		tag_info.setToolTip("Ways to write tags:\n\nNormal tags:\ntag1, tag2, tag3\n\n"+
					  "Namespaced tags:\nns1:tag1, ns1:tag2\n\nNamespaced tags with one or more"+
					  " tags under same namespace:\nns1:[tag1, tag2, tag3], ns2:[tag1, tag2]\n\n"+
					  "Those three ways of writing namespace & tags can be combined freely.\n"+
					  "Tags are seperated by a comma, NOT whitespace.\nNamespaces will be capitalized while tags"+
					  " will be lowercased.")
		tag_info.setToolTipDuration(99999999)
		tags_l.addWidget(tag_info)
		self.tags_edit = misc.CompleterTextEdit()
		self.tags_edit.setCompleter(misc.GCompleter(self, False, False))
		tags_l.addWidget(self.tags_edit, 3)
		self.tags_edit.setFixedHeight(70)
		self.tags_edit.setPlaceholderText("Press Tab to autocomplete (Ctrl + E to show popup)")
		self.type_box = QComboBox()
		self.type_box.addItems(["Manga", "Doujinshi", "Artist CG Sets", "Game CG Sets",
						  "Western", "Image Sets", "Non-H", "Cosplay", "Other"])
		self.type_box.setCurrentIndex(0)
		#self.type_box.currentIndexChanged[int].connect(self.doujin_show)
		#self.doujin_parent = QLineEdit()
		#self.doujin_parent.setVisible(False)
		self.status_box = QComboBox()
		self.status_box.addItems(["Unknown", "Ongoing", "Completed"])
		self.status_box.setCurrentIndex(0)
		self.pub_edit = QDateEdit()
		self.pub_edit.setCalendarPopup(True)
		self.pub_edit.setDate(QDate.currentDate())
		self.path_lbl = QLabel("")
		self.path_lbl.setWordWrap(True)

		link_layout = QHBoxLayout()
		self.link_lbl = QLabel("")
		self.link_lbl.setWordWrap(True)
		self.link_edit = QLineEdit()
		link_layout.addWidget(self.link_edit)
		link_layout.addWidget(self.link_lbl)
		self.link_edit.hide()
		self.link_btn = QPushButton("Modify")
		self.link_btn.setFixedWidth(50)
		self.link_btn2 = QPushButton("Set")
		self.link_btn2.setFixedWidth(40)
		self.link_btn.clicked.connect(self.link_modify)
		self.link_btn2.clicked.connect(self.link_set)
		link_layout.addWidget(self.link_btn)
		link_layout.addWidget(self.link_btn2)
		self.link_btn2.hide()

		gallery_layout.addRow("Title:", self.title_edit)
		gallery_layout.addRow("Author:", self.author_edit)
		gallery_layout.addRow("Description:", self.descr_edit)
		gallery_layout.addRow("Language:", self.lang_box)
		gallery_layout.addRow("Tags:", tags_l)
		gallery_layout.addRow("Type:", self.type_box)
		gallery_layout.addRow("Status:", self.status_box)
		gallery_layout.addRow("Publication Date:", self.pub_edit)
		gallery_layout.addRow("Path:", self.path_lbl)
		gallery_layout.addRow("Link:", link_layout)

		self.title_edit.setFocus()

	def _find_combobox_match(self, combobox, key, default):
		f_index = combobox.findText(key, Qt.MatchFixedString)
		try:
			combobox.setCurrentIndex(f_index)
		except:
			combobox.setCurrentIndex(default)

	def setGallery(self, gallery):
		"To be used for when editing a gallery"
		self.gallery = gallery

		self.url_edit.setText(gallery.link)

		self.title_edit.setText(gallery.title)
		self.author_edit.setText(gallery.artist)
		self.descr_edit.setText(gallery.info)

		self.tags_edit.setText(utils.tag_to_string(gallery.tags))


		self._find_combobox_match(self.lang_box, gallery.language, 2)
		self._find_combobox_match(self.type_box, gallery.type, 0)
		self._find_combobox_match(self.status_box, gallery.status, 0)

		gallery_pub_date = "{}".format(gallery.pub_date).split(' ')
		try:
			self.gallery_time = datetime.strptime(gallery_pub_date[1], '%H:%M:%S').time()
		except IndexError:
			pass
		qdate_pub_date = QDate.fromString(gallery_pub_date[0], "yyyy-MM-dd")
		self.pub_edit.setDate(qdate_pub_date)

		self.link_lbl.setText(gallery.link)
		self.path_lbl.setText(gallery.path)

	def newUI(self):

		f_local = QGroupBox("Directory/Archive")
		f_local.setCheckable(False)
		self.main_layout.addWidget(f_local)
		local_layout = QHBoxLayout()
		f_local.setLayout(local_layout)

		choose_folder = QPushButton("From Directory")
		choose_folder.clicked.connect(lambda: self.choose_dir('f'))
		local_layout.addWidget(choose_folder)

		choose_archive = QPushButton("From Archive")
		choose_archive.clicked.connect(lambda: self.choose_dir('a'))
		local_layout.addWidget(choose_archive)

		self.file_exists_lbl = QLabel()
		local_layout.addWidget(self.file_exists_lbl)
		self.file_exists_lbl.hide()

	def choose_dir(self, mode):
		"""
		Pass which mode to open the folder explorer in:
		'f': directory
		'a': files
		Or pass a predefined path
		"""
		self.done.show()
		self.file_exists_lbl.hide()
		if mode == 'a':
			name = QFileDialog.getOpenFileName(self, 'Choose archive',
											  filter=utils.FILE_FILTER)
			name = name[0]
		elif mode == 'f':
			name = QFileDialog.getExistingDirectory(self, 'Choose folder')
		elif mode:
			if os.path.exists(mode):
				name = mode
			else:
				return None
		if not name:
			return
		head, tail = os.path.split(name)
		name = os.path.join(head, tail)
		parsed = utils.title_parser(tail)
		self.title_edit.setText(parsed['title'])
		self.author_edit.setText(parsed['artist'])
		self.path_lbl.setText(name)
		l_i = self.lang_box.findText(parsed['language'])
		if l_i != -1:
			self.lang_box.setCurrentIndex(l_i)
		if gallerydb.GalleryDB.check_exists(name):
			self.file_exists_lbl.setText('<font color="red">Gallery already exists.</font>')
			self.file_exists_lbl.show()
		# check galleries
		gs = 1
		if name.endswith(utils.ARCHIVE_FILES):
			gs = len(utils.check_archive(name))
		elif os.path.isdir(name):
			g_dirs, g_archs = utils.recursive_gallery_check(name)
			gs = len(g_dirs) + len(g_archs)
		if gs == 0:
			self.file_exists_lbl.setText('<font color="red">Invalid gallery source.</font>')
			self.file_exists_lbl.show()
			self.done.hide()
		if app_constants.SUBFOLDER_AS_GALLERY:
			if gs > 1:
				self.file_exists_lbl.setText('<font color="red">More than one galleries detected in source! Use other methods to add.</font>')
				self.file_exists_lbl.show()
				self.done.hide()

	def check(self):
		if len(self.title_edit.text()) is 0:
			self.title_edit.setFocus()
			self.title_edit.setStyleSheet("border-style:outset;border-width:2px;border-color:red;")
			return False
		elif len(self.author_edit.text()) is 0:
			self.author_edit.setText("Unknown")

		if len(self.path_lbl.text()) == 0 or self.path_lbl.text() == 'No path specified':
			self.path_lbl.setStyleSheet("color:red")
			self.path_lbl.setText('No path specified')
			return False

		return True

	def set_chapters(self, gallery_object, add_to_model=True):
		path = gallery_object.path
		chap_container = gallerydb.ChaptersContainer(gallery_object)
		metafile = utils.GMetafile()
		try:
			log_d('Listing dir...')
			con = scandir.scandir(path) # list all folders in gallery dir
			log_i('Gallery source is a directory')
			log_d('Sorting')
			chapters = sorted([sub.path for sub in con if sub.is_dir() or sub.name.endswith(utils.ARCHIVE_FILES)]) #subfolders
			# if gallery has chapters divided into sub folders
			if len(chapters) != 0:
				log_d('Chapters divided in folders..')
				for ch in chapters:
					chap = chap_container.create_chapter()
					chap.title = utils.title_parser(ch)['title']
					chap.path = os.path.join(path, ch)
					metafile.update(utils.GMetafile(chap.path))
					chap.pages = len(list(scandir.scandir(chap.path)))

			else: #else assume that all images are in gallery folder
				chap = chap_container.create_chapter()
				chap.title = utils.title_parser(os.path.split(path)[1])['title']
				chap.path = path
				metafile.update(utils.GMetafile(path))
				chap.pages = len(list(scandir.scandir(path)))

		except NotADirectoryError:
			if path.endswith(utils.ARCHIVE_FILES):
				gallery_object.is_archive = 1
				log_i("Gallery source is an archive")
				archive_g = sorted(utils.check_archive(path))
				for g in archive_g:
					chap = chap_container.create_chapter()
					chap.path = g
					chap.in_archive = 1
					metafile.update(utils.GMetafile(g, path))
					arch = utils.ArchiveFile(path)
					chap.pages = len(arch.dir_contents(g))
					arch.close()

		metafile.apply_gallery(gallery_object)
		if add_to_model:
			self.SERIES.emit([gallery_object])
			log_d('Sent gallery to model')
		

	def reject(self):
		if self.check():
			msgbox = QMessageBox()
			msgbox.setText("<font color='red'><b>Noo oniichan! You were about to add a new gallery.</b></font>")
			msgbox.setInformativeText("Do you really want to discard?")
			msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
			msgbox.setDefaultButton(QMessageBox.No)
			if msgbox.exec() == QMessageBox.Yes:
				self.close()
		else:
			self.close()

	def web_metadata(self, url, btn_widget, pgr_widget):
		self.link_lbl.setText(url)
		f = fetch.Fetch()
		thread = QThread(self)
		thread.setObjectName('Gallerydialog web metadata')
		btn_widget.hide()
		pgr_widget.show()

		def status(stat):
			def do_hide():
				try:
					pgr_widget.hide()
					btn_widget.show()
				except RuntimeError:
					pass

			if stat:
				do_hide()
			else:
				danger = """QProgressBar::chunk {
					background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0,stop: 0 #FF0350,stop: 0.4999 #FF0020,stop: 0.5 #FF0019,stop: 1 #FF0000 );
					border-bottom-right-radius: 5px;
					border-bottom-left-radius: 5px;
					border: .px solid black;}"""
				pgr_widget.setStyleSheet(danger)
				QTimer.singleShot(3000, do_hide)
			f.deleteLater()

		def gallery_picker(gallery, title_url_list, q):
			self.parent_widget._web_metadata_picker(gallery, title_url_list, q, self)

		try:
			dummy_gallery = self.make_gallery(self.gallery)
		except AttributeError:
			dummy_gallery = self.make_gallery(gallerydb.Gallery(), False)
		if not dummy_gallery:
			status(False)
			return None

		dummy_gallery.link = url
		f.galleries = [dummy_gallery]
		f.moveToThread(thread)
		f.GALLERY_PICKER.connect(gallery_picker)
		f.GALLERY_EMITTER.connect(self.set_web_metadata)
		thread.started.connect(f.auto_web_metadata)
		thread.finished.connect(thread.deleteLater)
		f.FINISHED.connect(status)
		thread.start()
			
	def set_web_metadata(self, metadata):
		assert isinstance(metadata, gallerydb.Gallery)
		self.link_lbl.setText(metadata.link)
		self.title_edit.setText(metadata.title)
		self.author_edit.setText(metadata.artist)
		tags = ""
		lang = ['English', 'Japanese']
		self._find_combobox_match(self.lang_box, metadata.language, 2)
		self.tags_edit.setText(utils.tag_to_string(metadata.tags))
		pub_string = "{}".format(metadata.pub_date)
		pub_date = QDate.fromString(pub_string.split()[0], "yyyy-MM-dd")
		self.pub_edit.setDate(pub_date)
		self._find_combobox_match(self.type_box, metadata.type, 0)

	def make_gallery(self, new_gallery, add_to_model=True, new=False):
		if self.check():
			new_gallery.title = self.title_edit.text()
			log_d('Adding gallery title')
			new_gallery.artist = self.author_edit.text()
			log_d('Adding gallery artist')
			log_d('Adding gallery path')
			if new and app_constants.MOVE_IMPORTED_GALLERIES:
				app_constants.OVERRIDE_MONITOR = True
				new_gallery.path = utils.move_files(self.path_lbl.text())
			else:
				new_gallery.path = self.path_lbl.text()
			new_gallery.info = self.descr_edit.toPlainText()
			log_d('Adding gallery descr')
			new_gallery.type = self.type_box.currentText()
			log_d('Adding gallery type')
			new_gallery.language = self.lang_box.currentText()
			log_d('Adding gallery lang')
			new_gallery.status = self.status_box.currentText()
			log_d('Adding gallery status')
			new_gallery.tags = utils.tag_to_dict(self.tags_edit.toPlainText())
			log_d('Adding gallery: tagging to dict')
			qpub_d = self.pub_edit.date().toString("ddMMyyyy")
			dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date()
			try:
				d_t = self.gallery_time
			except AttributeError:
				d_t = datetime.now().time().replace(microsecond=0)
			dpub_d = datetime.combine(dpub_d, d_t)
			new_gallery.pub_date = dpub_d
			log_d('Adding gallery pub date')
			new_gallery.link = self.link_lbl.text()
			log_d('Adding gallery link')
			if not new_gallery.chapters:
				log_d('Starting chapters')
				thread = threading.Thread(target=self.set_chapters, args=(new_gallery,add_to_model), daemon=True)
				thread.start()
				thread.join()
				log_d('Finished chapters')
			return new_gallery


	def link_set(self):
		t = self.link_edit.text()
		self.link_edit.hide()
		self.link_lbl.show()
		self.link_lbl.setText(t)
		self.link_btn2.hide()
		self.link_btn.show() 

	def link_modify(self):
		t = self.link_lbl.text()
		self.link_lbl.hide()
		self.link_edit.show()
		self.link_edit.setText(t)
		self.link_btn.hide()
		self.link_btn2.show()

	def accept(self):
		new_gallery = self.make_gallery(gallerydb.Gallery(), new=True)

		if new_gallery:
			self.close()

	def accept_edit(self):
		new_gallery = self.make_gallery(self.gallery)
		#for ser in self.gallery:
		if new_gallery:
			self.SERIES_EDIT.emit([new_gallery], self.position)
			self.close()

	def reject_edit(self):
		self.close()
Ejemplo n.º 46
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.createPreviewGroupBox()
        self.createGeneralOptionsGroupBox()
        self.createDatesGroupBox()
        self.createTextFormatsGroupBox()

        layout = QGridLayout()
        layout.addWidget(self.previewGroupBox, 0, 0)
        layout.addWidget(self.generalOptionsGroupBox, 0, 1)
        layout.addWidget(self.datesGroupBox, 1, 0)
        layout.addWidget(self.textFormatsGroupBox, 1, 1)
        layout.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(layout)

        self.previewLayout.setRowMinimumHeight(0,
                self.calendar.sizeHint().height())
        self.previewLayout.setColumnMinimumWidth(0,
                self.calendar.sizeHint().width())

        self.setWindowTitle("Calendar Widget")

    def localeChanged(self, index):
        self.calendar.setLocale(self.localeCombo.itemData(index))

    def firstDayChanged(self, index):
        self.calendar.setFirstDayOfWeek(
                Qt.DayOfWeek(self.firstDayCombo.itemData(index)))

    def selectionModeChanged(self, index):
        self.calendar.setSelectionMode(
                QCalendarWidget.SelectionMode(
                        self.selectionModeCombo.itemData(index)))

    def horizontalHeaderChanged(self, index):
        self.calendar.setHorizontalHeaderFormat(
                QCalendarWidget.HorizontalHeaderFormat(
                        self.horizontalHeaderCombo.itemData(index)))

    def verticalHeaderChanged(self, index):
        self.calendar.setVerticalHeaderFormat(
                QCalendarWidget.VerticalHeaderFormat(
                        self.verticalHeaderCombo.itemData(index)))

    def selectedDateChanged(self):
        self.currentDateEdit.setDate(self.calendar.selectedDate())

    def minimumDateChanged(self, date):
        self.calendar.setMinimumDate(date)
        self.maximumDateEdit.setDate(self.calendar.maximumDate())

    def maximumDateChanged(self, date):
        self.calendar.setMaximumDate(date)
        self.minimumDateEdit.setDate(self.calendar.minimumDate())

    def weekdayFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
                Qt.GlobalColor(
                        self.weekdayColorCombo.itemData(
                                self.weekdayColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Monday, format)
        self.calendar.setWeekdayTextFormat(Qt.Tuesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Wednesday, format)
        self.calendar.setWeekdayTextFormat(Qt.Thursday, format)
        self.calendar.setWeekdayTextFormat(Qt.Friday, format)

    def weekendFormatChanged(self):
        format = QTextCharFormat()
        format.setForeground(
                Qt.GlobalColor(
                        self.weekendColorCombo.itemData(
                                self.weekendColorCombo.currentIndex())))

        self.calendar.setWeekdayTextFormat(Qt.Saturday, format)
        self.calendar.setWeekdayTextFormat(Qt.Sunday, format)

    def reformatHeaders(self):
        text = self.headerTextFormatCombo.currentText()
        format = QTextCharFormat()

        if text == "Bold":
            format.setFontWeight(QFont.Bold)
        elif text == "Italic":
            format.setFontItalic(True)
        elif text == "Green":
            format.setForeground(Qt.green)

        self.calendar.setHeaderTextFormat(format)

    def reformatCalendarPage(self):
        if self.firstFridayCheckBox.isChecked():
            firstFriday = QDate(self.calendar.yearShown(),
                    self.calendar.monthShown(), 1)

            while firstFriday.dayOfWeek() != Qt.Friday:
                firstFriday = firstFriday.addDays(1)

            firstFridayFormat = QTextCharFormat()
            firstFridayFormat.setForeground(Qt.blue)

            self.calendar.setDateTextFormat(firstFriday, firstFridayFormat)

        # May 1st in Red takes precedence.
        if self.mayFirstCheckBox.isChecked():
            mayFirst = QDate(self.calendar.yearShown(), 5, 1)

            mayFirstFormat = QTextCharFormat()
            mayFirstFormat.setForeground(Qt.red)

            self.calendar.setDateTextFormat(mayFirst, mayFirstFormat)

    def createPreviewGroupBox(self):
        self.previewGroupBox = QGroupBox("Preview")

        self.calendar = QCalendarWidget()
        self.calendar.setMinimumDate(QDate(1900, 1, 1))
        self.calendar.setMaximumDate(QDate(3000, 1, 1))
        self.calendar.setGridVisible(True)
        self.calendar.currentPageChanged.connect(self.reformatCalendarPage)

        self.previewLayout = QGridLayout()
        self.previewLayout.addWidget(self.calendar, 0, 0, Qt.AlignCenter)
        self.previewGroupBox.setLayout(self.previewLayout)
 
    def createGeneralOptionsGroupBox(self):
        self.generalOptionsGroupBox = QGroupBox("General Options")

        self.localeCombo = QComboBox()

        curLocaleIndex = -1
        index = 0

        this_language = self.locale().nativeLanguageName()
        this_country = self.locale().nativeCountryName()

        for locale in QLocale.matchingLocales(QLocale.AnyLanguage, QLocale.AnyScript, QLocale.AnyCountry):
            language = locale.nativeLanguageName()
            country = locale.nativeCountryName()

            if language == this_language and country == this_country:
                curLocaleIndex = index

            self.localeCombo.addItem('%s/%s' % (language, country), locale)
            index += 1

        if curLocaleIndex != -1:
            self.localeCombo.setCurrentIndex(curLocaleIndex)

        self.localeLabel = QLabel("&Locale")
        self.localeLabel.setBuddy(self.localeCombo)

        self.firstDayCombo = QComboBox()
        self.firstDayCombo.addItem("Sunday", Qt.Sunday)
        self.firstDayCombo.addItem("Monday", Qt.Monday)
        self.firstDayCombo.addItem("Tuesday", Qt.Tuesday)
        self.firstDayCombo.addItem("Wednesday", Qt.Wednesday)
        self.firstDayCombo.addItem("Thursday", Qt.Thursday)
        self.firstDayCombo.addItem("Friday", Qt.Friday)
        self.firstDayCombo.addItem("Saturday", Qt.Saturday)

        self.firstDayLabel = QLabel("Wee&k starts on:")
        self.firstDayLabel.setBuddy(self.firstDayCombo)

        self.selectionModeCombo = QComboBox()
        self.selectionModeCombo.addItem("Single selection",
                QCalendarWidget.SingleSelection)
        self.selectionModeCombo.addItem("None",
                QCalendarWidget.NoSelection)
        self.selectionModeLabel = QLabel("&Selection mode:")
        self.selectionModeLabel.setBuddy(self.selectionModeCombo)

        self.gridCheckBox = QCheckBox("&Grid")
        self.gridCheckBox.setChecked(self.calendar.isGridVisible())

        self.navigationCheckBox = QCheckBox("&Navigation bar")
        self.navigationCheckBox.setChecked(True)

        self.horizontalHeaderCombo = QComboBox()
        self.horizontalHeaderCombo.addItem("Single letter day names",
                QCalendarWidget.SingleLetterDayNames)
        self.horizontalHeaderCombo.addItem("Short day names",
                QCalendarWidget.ShortDayNames)
        self.horizontalHeaderCombo.addItem("Long day names",
                QCalendarWidget.LongDayNames)
        self.horizontalHeaderCombo.addItem("None",
                QCalendarWidget.NoHorizontalHeader)
        self.horizontalHeaderCombo.setCurrentIndex(1)

        self.horizontalHeaderLabel = QLabel("&Horizontal header:")
        self.horizontalHeaderLabel.setBuddy(self.horizontalHeaderCombo)

        self.verticalHeaderCombo = QComboBox()
        self.verticalHeaderCombo.addItem("ISO week numbers",
                QCalendarWidget.ISOWeekNumbers)
        self.verticalHeaderCombo.addItem("None",
                QCalendarWidget.NoVerticalHeader)

        self.verticalHeaderLabel = QLabel("&Vertical header:")
        self.verticalHeaderLabel.setBuddy(self.verticalHeaderCombo)

        self.localeCombo.currentIndexChanged.connect(self.localeChanged)
        self.firstDayCombo.currentIndexChanged.connect(self.firstDayChanged)
        self.selectionModeCombo.currentIndexChanged.connect(
                self.selectionModeChanged)
        self.gridCheckBox.toggled.connect(self.calendar.setGridVisible)
        self.navigationCheckBox.toggled.connect(
                self.calendar.setNavigationBarVisible)
        self.horizontalHeaderCombo.currentIndexChanged.connect(
                self.horizontalHeaderChanged)
        self.verticalHeaderCombo.currentIndexChanged.connect(
                self.verticalHeaderChanged)

        checkBoxLayout = QHBoxLayout()
        checkBoxLayout.addWidget(self.gridCheckBox)
        checkBoxLayout.addStretch()
        checkBoxLayout.addWidget(self.navigationCheckBox)

        outerLayout = QGridLayout()
        outerLayout.addWidget(self.localeLabel, 0, 0)
        outerLayout.addWidget(self.localeCombo, 0, 1)
        outerLayout.addWidget(self.firstDayLabel, 1, 0)
        outerLayout.addWidget(self.firstDayCombo, 1, 1)
        outerLayout.addWidget(self.selectionModeLabel, 2, 0)
        outerLayout.addWidget(self.selectionModeCombo, 2, 1)
        outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
        outerLayout.addWidget(self.horizontalHeaderLabel, 4, 0)
        outerLayout.addWidget(self.horizontalHeaderCombo, 4, 1)
        outerLayout.addWidget(self.verticalHeaderLabel, 5, 0)
        outerLayout.addWidget(self.verticalHeaderCombo, 5, 1)
        self.generalOptionsGroupBox.setLayout(outerLayout)

        self.firstDayChanged(self.firstDayCombo.currentIndex())
        self.selectionModeChanged(self.selectionModeCombo.currentIndex())
        self.horizontalHeaderChanged(self.horizontalHeaderCombo.currentIndex())
        self.verticalHeaderChanged(self.verticalHeaderCombo.currentIndex())
 
    def createDatesGroupBox(self):
        self.datesGroupBox = QGroupBox(self.tr("Dates"))

        self.minimumDateEdit = QDateEdit()
        self.minimumDateEdit.setDisplayFormat('MMM d yyyy')
        self.minimumDateEdit.setDateRange(self.calendar.minimumDate(),
                                          self.calendar.maximumDate())
        self.minimumDateEdit.setDate(self.calendar.minimumDate())

        self.minimumDateLabel = QLabel("&Minimum Date:")
        self.minimumDateLabel.setBuddy(self.minimumDateEdit)

        self.currentDateEdit = QDateEdit()
        self.currentDateEdit.setDisplayFormat('MMM d yyyy')
        self.currentDateEdit.setDate(self.calendar.selectedDate())
        self.currentDateEdit.setDateRange(self.calendar.minimumDate(),
                self.calendar.maximumDate())

        self.currentDateLabel = QLabel("&Current Date:")
        self.currentDateLabel.setBuddy(self.currentDateEdit)

        self.maximumDateEdit = QDateEdit()
        self.maximumDateEdit.setDisplayFormat('MMM d yyyy')
        self.maximumDateEdit.setDateRange(self.calendar.minimumDate(),
                self.calendar.maximumDate())
        self.maximumDateEdit.setDate(self.calendar.maximumDate())

        self.maximumDateLabel = QLabel("Ma&ximum Date:")
        self.maximumDateLabel.setBuddy(self.maximumDateEdit)

        self.currentDateEdit.dateChanged.connect(self.calendar.setSelectedDate)
        self.calendar.selectionChanged.connect(self.selectedDateChanged)
        self.minimumDateEdit.dateChanged.connect(self.minimumDateChanged)
        self.maximumDateEdit.dateChanged.connect(self.maximumDateChanged)
 
        dateBoxLayout = QGridLayout()
        dateBoxLayout.addWidget(self.currentDateLabel, 1, 0)
        dateBoxLayout.addWidget(self.currentDateEdit, 1, 1)
        dateBoxLayout.addWidget(self.minimumDateLabel, 0, 0)
        dateBoxLayout.addWidget(self.minimumDateEdit, 0, 1)
        dateBoxLayout.addWidget(self.maximumDateLabel, 2, 0)
        dateBoxLayout.addWidget(self.maximumDateEdit, 2, 1)
        dateBoxLayout.setRowStretch(3, 1)

        self.datesGroupBox.setLayout(dateBoxLayout)

    def createTextFormatsGroupBox(self):
        self.textFormatsGroupBox = QGroupBox("Text Formats")

        self.weekdayColorCombo = self.createColorComboBox()
        self.weekdayColorCombo.setCurrentIndex(
                self.weekdayColorCombo.findText("Black"))

        self.weekdayColorLabel = QLabel("&Weekday color:")
        self.weekdayColorLabel.setBuddy(self.weekdayColorCombo)

        self.weekendColorCombo = self.createColorComboBox()
        self.weekendColorCombo.setCurrentIndex(
                self.weekendColorCombo.findText("Red"))

        self.weekendColorLabel = QLabel("Week&end color:")
        self.weekendColorLabel.setBuddy(self.weekendColorCombo)

        self.headerTextFormatCombo = QComboBox()
        self.headerTextFormatCombo.addItem("Bold")
        self.headerTextFormatCombo.addItem("Italic")
        self.headerTextFormatCombo.addItem("Plain")

        self.headerTextFormatLabel = QLabel("&Header text:")
        self.headerTextFormatLabel.setBuddy(self.headerTextFormatCombo)

        self.firstFridayCheckBox = QCheckBox("&First Friday in blue")

        self.mayFirstCheckBox = QCheckBox("May &1 in red")

        self.weekdayColorCombo.currentIndexChanged.connect(
                self.weekdayFormatChanged)
        self.weekendColorCombo.currentIndexChanged.connect(
                self.weekendFormatChanged)
        self.headerTextFormatCombo.currentIndexChanged.connect(
                self.reformatHeaders)
        self.firstFridayCheckBox.toggled.connect(self.reformatCalendarPage)
        self.mayFirstCheckBox.toggled.connect(self.reformatCalendarPage)

        checkBoxLayout = QHBoxLayout()
        checkBoxLayout.addWidget(self.firstFridayCheckBox)
        checkBoxLayout.addStretch()
        checkBoxLayout.addWidget(self.mayFirstCheckBox)

        outerLayout = QGridLayout()
        outerLayout.addWidget(self.weekdayColorLabel, 0, 0)
        outerLayout.addWidget(self.weekdayColorCombo, 0, 1)
        outerLayout.addWidget(self.weekendColorLabel, 1, 0)
        outerLayout.addWidget(self.weekendColorCombo, 1, 1)
        outerLayout.addWidget(self.headerTextFormatLabel, 2, 0)
        outerLayout.addWidget(self.headerTextFormatCombo, 2, 1)
        outerLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
        self.textFormatsGroupBox.setLayout(outerLayout)

        self.weekdayFormatChanged()
        self.weekendFormatChanged()

        self.reformatHeaders()
        self.reformatCalendarPage()
 
    def createColorComboBox(self):
        comboBox = QComboBox()
        comboBox.addItem("Red", Qt.red)
        comboBox.addItem("Blue", Qt.blue)
        comboBox.addItem("Black", Qt.black)
        comboBox.addItem("Magenta", Qt.magenta)

        return comboBox
Ejemplo n.º 47
0
	def commonUI(self):
		f_web = QGroupBox("Metadata from the Web")
		f_web.setCheckable(False)
		self.main_layout.addWidget(f_web)
		web_main_layout = QVBoxLayout()
		web_info = misc.ClickedLabel("Which gallery URLs are supported? (hover)", parent=self)
		web_info.setToolTip(app_constants.SUPPORTED_METADATA_URLS)
		web_info.setToolTipDuration(999999999)
		web_main_layout.addWidget(web_info)
		web_layout = QHBoxLayout()
		web_main_layout.addLayout(web_layout)
		f_web.setLayout(web_main_layout)

		f_gallery = QGroupBox("Gallery Info")
		f_gallery.setCheckable(False)
		self.main_layout.addWidget(f_gallery)
		gallery_layout = QFormLayout()
		f_gallery.setLayout(gallery_layout)

		def basic_web(name):
			return QLabel(name), QLineEdit(), QPushButton("Get metadata"), QProgressBar()

		url_lbl, self.url_edit, url_btn, url_prog = basic_web("URL:")
		url_btn.clicked.connect(lambda: self.web_metadata(self.url_edit.text(), url_btn,
											url_prog))
		url_prog.setTextVisible(False)
		url_prog.setMinimum(0)
		url_prog.setMaximum(0)
		web_layout.addWidget(url_lbl, 0, Qt.AlignLeft)
		web_layout.addWidget(self.url_edit, 0)
		web_layout.addWidget(url_btn, 0, Qt.AlignRight)
		web_layout.addWidget(url_prog, 0, Qt.AlignRight)
		self.url_edit.setPlaceholderText("Insert supported gallery URLs or just press the button!")
		url_prog.hide()

		self.title_edit = QLineEdit()
		self.author_edit = QLineEdit()
		author_completer = misc.GCompleter(self, False, True, False)
		author_completer.setCaseSensitivity(Qt.CaseInsensitive)
		self.author_edit.setCompleter(author_completer)
		self.descr_edit = QTextEdit()
		self.descr_edit.setAcceptRichText(True)
		self.lang_box = QComboBox()
		self.lang_box.addItems(app_constants.G_LANGUAGES)
		self.lang_box.addItems(app_constants.G_CUSTOM_LANGUAGES)
		self._find_combobox_match(self.lang_box, app_constants.G_DEF_LANGUAGE, 0)
		tags_l = QVBoxLayout()
		tag_info = misc.ClickedLabel("How do i write namespace & tags? (hover)", parent=self)
		tag_info.setToolTip("Ways to write tags:\n\nNormal tags:\ntag1, tag2, tag3\n\n"+
					  "Namespaced tags:\nns1:tag1, ns1:tag2\n\nNamespaced tags with one or more"+
					  " tags under same namespace:\nns1:[tag1, tag2, tag3], ns2:[tag1, tag2]\n\n"+
					  "Those three ways of writing namespace & tags can be combined freely.\n"+
					  "Tags are seperated by a comma, NOT whitespace.\nNamespaces will be capitalized while tags"+
					  " will be lowercased.")
		tag_info.setToolTipDuration(99999999)
		tags_l.addWidget(tag_info)
		self.tags_edit = misc.CompleterTextEdit()
		self.tags_edit.setCompleter(misc.GCompleter(self, False, False))
		tags_l.addWidget(self.tags_edit, 3)
		self.tags_edit.setPlaceholderText("Press Tab to autocomplete (Ctrl + E to show popup)")
		self.type_box = QComboBox()
		self.type_box.addItems(app_constants.G_TYPES)
		self._find_combobox_match(self.type_box, app_constants.G_DEF_TYPE, 0)
		#self.type_box.currentIndexChanged[int].connect(self.doujin_show)
		#self.doujin_parent = QLineEdit()
		#self.doujin_parent.setVisible(False)
		self.status_box = QComboBox()
		self.status_box.addItems(app_constants.G_STATUS)
		self._find_combobox_match(self.status_box, app_constants.G_DEF_STATUS, 0)
		self.pub_edit = QDateEdit()
		self.pub_edit.setCalendarPopup(True)
		self.pub_edit.setDate(QDate.currentDate())
		self.path_lbl = misc.ClickedLabel("")
		self.path_lbl.setWordWrap(True)
		self.path_lbl.clicked.connect(lambda a: utils.open_path(a, a) if a else None)

		link_layout = QHBoxLayout()
		self.link_lbl = QLabel("")
		self.link_lbl.setWordWrap(True)
		self.link_edit = QLineEdit()
		link_layout.addWidget(self.link_edit)
		link_layout.addWidget(self.link_lbl)
		self.link_edit.hide()
		self.link_btn = QPushButton("Modify")
		self.link_btn.setFixedWidth(50)
		self.link_btn2 = QPushButton("Set")
		self.link_btn2.setFixedWidth(40)
		self.link_btn.clicked.connect(self.link_modify)
		self.link_btn2.clicked.connect(self.link_set)
		link_layout.addWidget(self.link_btn)
		link_layout.addWidget(self.link_btn2)
		self.link_btn2.hide()

		gallery_layout.addRow("Title:", self.title_edit)
		gallery_layout.addRow("Author:", self.author_edit)
		gallery_layout.addRow("Description:", self.descr_edit)
		gallery_layout.addRow("Language:", self.lang_box)
		gallery_layout.addRow("Tags:", tags_l)
		gallery_layout.addRow("Type:", self.type_box)
		gallery_layout.addRow("Status:", self.status_box)
		gallery_layout.addRow("Publication Date:", self.pub_edit)
		gallery_layout.addRow("Path:", self.path_lbl)
		gallery_layout.addRow("Link:", link_layout)

		self.title_edit.setFocus()
Ejemplo n.º 48
0
	def setSeries(self, series):
		"To be used for when editing a series"
		self.series = series
		main_layout = QVBoxLayout()

		f_web = QGroupBox("Fetch metadata from Web")
		f_web.setCheckable(False)
		main_layout.addWidget(f_web)
		web_layout = QHBoxLayout()
		f_web.setLayout(web_layout)

		f_series = QGroupBox("Series Info")
		f_series.setCheckable(False)
		main_layout.addWidget(f_series)
		series_layout = QFormLayout()
		f_series.setLayout(series_layout)

		def basic_web(name):
			return QLabel(name), QLineEdit(), QPushButton("Fetch")

		exh_lbl, exh_edit, exh_btn = basic_web("ExHentai:")
		web_layout.addWidget(exh_lbl, 0, Qt.AlignLeft)
		web_layout.addWidget(exh_edit, 0)
		web_layout.addWidget(exh_btn, 0, Qt.AlignRight)

		self.title_edit = QLineEdit()
		self.title_edit.setText(series.title)
		self.author_edit = QLineEdit()
		self.author_edit.setText(series.artist)
		self.descr_edit = QTextEdit()
		self.descr_edit.setText(series.info)
		self.descr_edit.setAcceptRichText(True)
		self.descr_edit.setFixedHeight(70)
		self.lang_box = QComboBox()
		self.lang_box.addItems(["English", "Japanese", "Other"])
		if series.language is "English":
			self.lang_box.setCurrentIndex(0)
		elif series.language is "Japanese":
			self.lang_box.setCurrentIndex(1)
		else:
			self.lang_box.setCurrentIndex(2)

		self.tags_edit = QLineEdit() #TODO Finish this..
		self.tags_edit.setPlaceholderText("namespace1:tag1, tag2, namespace3:tag3, etc..")
		self.type_box = QComboBox()
		self.type_box.addItems(["Manga", "Doujinshi", "Other"])
		if series.type is "Manga":
			self.type_box.setCurrentIndex(0)
		elif series.type is "Doujinshi":
			self.type_box.setCurrentIndex(1)
		else:
			self.type_box.setCurrentIndex(2)
		#self.type_box.currentIndexChanged[int].connect(self.doujin_show)
		#self.doujin_parent = QLineEdit()
		#self.doujin_parent.setVisible(False)
		self.status_box = QComboBox()
		self.status_box.addItems(["Unknown", "Ongoing", "Completed"])
		if series.status is "Ongoing":
			self.status_box.setCurrentIndex(1)
		elif series.status is "Completed":
			self.status_box.setCurrentIndex(2)
		else:
			self.status_box.setCurrentIndex(0)

		self.pub_edit = QDateEdit() # TODO: Finish this..
		self.pub_edit.setCalendarPopup(True)
		series_pub_date = "{}".format(series.pub_date)
		qdate_pub_date = QDate.fromString(series_pub_date, "yyyy-MM-dd")
		self.pub_edit.setDate(qdate_pub_date)
		self.path_lbl = QLabel("unspecified...")
		self.path_lbl.setWordWrap(True)
		self.path_lbl.setText(series.path)

		series_layout.addRow("Title:", self.title_edit)
		series_layout.addRow("Author:", self.author_edit)
		series_layout.addRow("Description:", self.descr_edit)
		series_layout.addRow("Language:", self.lang_box)
		series_layout.addRow("Tags:", self.tags_edit)
		series_layout.addRow("Type:", self.type_box)
		series_layout.addRow("Publication Date:", self.pub_edit)
		series_layout.addRow("Path:", self.path_lbl)

		final_buttons = QHBoxLayout()
		final_buttons.setAlignment(Qt.AlignRight)
		main_layout.addLayout(final_buttons)
		done = QPushButton("Done")
		done.setDefault(True)
		done.clicked.connect(self.accept_edit)
		cancel = QPushButton("Cancel")
		cancel.clicked.connect(self.reject_edit)
		final_buttons.addWidget(cancel)
		final_buttons.addWidget(done)

		self.setLayout(main_layout)
Ejemplo n.º 49
0
    def __init__(self):
        super(DataWidget, self).__init__(None)
        self.read_data_file(config.HISTORIC_DATA)
        self.start_date = date(2016, 10, 1)
        self.end_date = date(2016, 11, 1)
        self.graph = GraphCanvas(self.data_frame)
        with open(config.LOGFILE, 'w', newline='') as logfile:
            logwriter = csv.writer(logfile)
            logwriter.writerow(config.headers)

        # options group box
        self.optionsGroupBox = QGroupBox("Options")
        options_layout = QVBoxLayout()
        date_range_layout = QFormLayout()
        start_date_label = QLabel("Start Date:")
        self.start_date_box = QDateEdit(self.start_date)
        self.start_date_box.setCalendarPopup(True)
        self.start_date_box.setDisplayFormat(config.DATE_DISPLAY_FORMAT)
        self.start_date_box.dateChanged.connect(self.plot)
        end_date_label = QLabel("End Date:")
        self.end_date_box = QDateEdit(self.end_date)
        self.end_date_box.setCalendarPopup(True)
        self.end_date_box.setDisplayFormat(config.DATE_DISPLAY_FORMAT)
        self.end_date_box.dateChanged.connect(self.plot)
        date_range_layout.addRow(start_date_label, self.start_date_box)
        date_range_layout.addRow(end_date_label, self.end_date_box)
        # days of week
        self.sundayCheckBox = QCheckBox("Sunday")
        self.mondayCheckBox = QCheckBox("Monday")
        self.tuesdayCheckBox = QCheckBox("Tuesday")
        self.wednesdayCheckBox = QCheckBox("Wednesday")
        self.thursdayCheckBox = QCheckBox("Thursday")
        self.fridayCheckBox = QCheckBox("Friday")
        self.saturdayCheckBox = QCheckBox("Saturday")
        self.sundayCheckBox.toggled.connect(self.plot)
        self.mondayCheckBox.toggled.connect(self.plot)
        self.tuesdayCheckBox.toggled.connect(self.plot)
        self.wednesdayCheckBox.toggled.connect(self.plot)
        self.thursdayCheckBox.toggled.connect(self.plot)
        self.fridayCheckBox.toggled.connect(self.plot)
        self.saturdayCheckBox.toggled.connect(self.plot)

        options_layout.addLayout(date_range_layout)
        options_layout.addWidget(self.sundayCheckBox)
        options_layout.addWidget(self.mondayCheckBox)
        options_layout.addWidget(self.tuesdayCheckBox)
        options_layout.addWidget(self.wednesdayCheckBox)
        options_layout.addWidget(self.thursdayCheckBox)
        options_layout.addWidget(self.fridayCheckBox)
        options_layout.addWidget(self.saturdayCheckBox)
        options_layout.addWidget(QPushButton("Button"))
        self.optionsGroupBox.setLayout(options_layout)

        # graph group box
        self.graphGroupBox = QGroupBox("Graph")
        graphLayout = QVBoxLayout()
        graphLayout.addWidget(self.graph)
        self.graphGroupBox.setLayout(graphLayout)

        # choice group box
        self.choiceGroupBox = QGroupBox("Choice")

        choice_layout = QVBoxLayout()

        choice_layout_1 = QHBoxLayout()
        choice_layout_1.addWidget(QLabel("A"))
        choice_layout_1.addWidget(QLabel("B"))
        choice_layout_1.addWidget(QLabel("C"))
        choice_layout_1.addWidget(QLabel("D"))

        choice_layout_2 = QHBoxLayout()
        self.decision_value_1 = QSpinBox()
        self.decision_value_2 = QSpinBox()
        self.decision_value_3 = QSpinBox()
        self.decision_value_4 = QSpinBox()
        choice_layout_2.addWidget(self.decision_value_1)
        choice_layout_2.addWidget(self.decision_value_2)
        choice_layout_2.addWidget(self.decision_value_3)
        choice_layout_2.addWidget(self.decision_value_4)

        choice_layout.addLayout(choice_layout_1)
        choice_layout.addLayout(choice_layout_2)

        self.decision_value_1.setValue(42)

        self.choiceGroupBox.setLayout(choice_layout)

        # count-down timer
        self.timerGroupBox = QGroupBox("Timer")
        timer_layout = QVBoxLayout()
        self.timerGroupBox.setLayout(timer_layout)
        self.count_down_timer = CountDownTimer()
        timer_layout.addWidget(self.count_down_timer.lcd)

        # central widget
        frame = QFrame(self)
        self.grid = QGridLayout(frame)
        self.grid.setSpacing(16)
        self.grid.setContentsMargins(16, 16, 16, 16)
        self.grid.addWidget(self.optionsGroupBox, 0, 0, 2, 1)
        self.grid.addWidget(self.graphGroupBox, 0, 1, 2, 1)
        self.grid.addWidget(self.timerGroupBox, 0, 2)
        self.grid.addWidget(self.choiceGroupBox, 2, 1)
        self.grid.setColumnStretch(0, 2)
        self.grid.setColumnStretch(1, 6)
        self.grid.setColumnStretch(2, 1)
        self.grid.setRowStretch(0, 1)
        self.grid.setRowStretch(1, 2)
        self.grid.setRowStretch(2, 2)
        self.setLayout(self.grid)
Ejemplo n.º 50
0
class BookLog(QWidget):
    NavigationMode, AddingMode, EditingMode = range(3)

    def __init__(self, parent=None):
        super(BookLog, self).__init__(parent)

        self.contacts = SortedDict()
        self.oldTitle = ''
        self.oldMemo = ''
        self.oldShoziflag = False
        self.oldIsbn = ''
        self.oldDokuryodate = QDate()
        self.currentMode = self.NavigationMode

        #ラベル
        titleLabel = QLabel("書名:")
        self.titleLine = QLineEdit()
        self.titleLine.setReadOnly(True)

        dokuryoLabel = QLabel("読了日:")
        self.dokuryodate = QDateEdit()
        self.dokuryodate.setReadOnly(True)


        memoLabel = QLabel("メモ:")
        self.memoText = QTextEdit()
        self.memoText.setReadOnly(True)

        isbnLabel = QLabel("ISBN:")
        self.isbnLine = QLineEdit()
        self.isbnLine.setReadOnly(True)

        shoziflag = QLabel("所持:")
        self.shoziflag = QCheckBox()

        self.addButton = QPushButton("&追加")
        self.addButton.show()
        self.editButton = QPushButton("&編集")
        self.editButton.setEnabled(False)
        self.removeButton = QPushButton("&削除")
        self.removeButton.setEnabled(False)
        self.findButton = QPushButton("&検索")
        self.findButton.setEnabled(False)
        self.submitButton = QPushButton("&挿入")
        self.submitButton.hide()
        self.cancelButton = QPushButton("&キャンセル")
        self.cancelButton.hide()

        self.nextButton = QPushButton("&次")
        self.nextButton.setEnabled(False)
        self.previousButton = QPushButton("&前")
        self.previousButton.setEnabled(False)

        self.loadButton = QPushButton("&Load...")
        self.loadButton.setToolTip("Load contacts from a file")
        self.saveButton = QPushButton("Sa&ve...")
        self.saveButton.setToolTip("Save contacts to a file")
        self.saveButton.setEnabled(False)

        self.exportButton = QPushButton("Ex&port")
        self.exportButton.setToolTip("Export as vCard")
        self.exportButton.setEnabled(False)

        self.dialog = FindDialog()

        self.addButton.clicked.connect(self.addContact)
        self.submitButton.clicked.connect(self.submitContact)
        self.editButton.clicked.connect(self.editContact)
        self.removeButton.clicked.connect(self.removeContact)
        #self.findButton.clicked.connect(self.findContact)
        self.cancelButton.clicked.connect(self.cancel)
        self.nextButton.clicked.connect(self.next)
        self.previousButton.clicked.connect(self.previous)
        self.loadButton.clicked.connect(self.loadFromFile)
        self.saveButton.clicked.connect(self.saveToFile)
        self.exportButton.clicked.connect(self.exportAsVCard)

        #self.createMenus()
        #topFiller = QWidget()
        #topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        buttonLayout1 = QVBoxLayout()
        buttonLayout1.addWidget(self.addButton)
        buttonLayout1.addWidget(self.editButton)
        buttonLayout1.addWidget(self.removeButton)
        buttonLayout1.addWidget(self.findButton)
        buttonLayout1.addWidget(self.submitButton)
        buttonLayout1.addWidget(self.cancelButton)
        buttonLayout1.addWidget(self.loadButton)
        buttonLayout1.addWidget(self.saveButton)
        buttonLayout1.addWidget(self.exportButton)
        buttonLayout1.addStretch()

        buttonLayout2 = QHBoxLayout()
        buttonLayout2.addWidget(self.previousButton)
        buttonLayout2.addWidget(self.nextButton)

        mainLayout = QGridLayout()
        mainLayout.addWidget(titleLabel, 0, 0)
        mainLayout.addWidget(self.titleLine, 0, 1)
        mainLayout.addWidget(memoLabel, 3, 0, Qt.AlignTop)
        mainLayout.addWidget(self.memoText, 3, 1)
        mainLayout.addWidget(dokuryoLabel, 2, 0)
        mainLayout.addWidget(self.dokuryodate, 2, 1)
        mainLayout.addWidget(isbnLabel, 1, 0)
        mainLayout.addWidget(self.isbnLine, 1, 1)
        mainLayout.addWidget(shoziflag, 4, 0)
        mainLayout.addWidget(self.shoziflag, 4, 1)
        mainLayout.addLayout(buttonLayout1, 6, 2)
        mainLayout.addLayout(buttonLayout2, 5, 1)
        #テーブル

        self.table = QTableWidget(100, 5,)
        self.table.setHorizontalHeaderLabels(["書名", "ISBN", "読了日", "メモ", "所持"])
        self.table.verticalHeader().setVisible(False)
        #for i, (title, memo) in enumerate(tableData):

        i = 0
        for title, obj in self.contacts.items():
            titleItem = QTableWidgetItem(title)
            memoItem = QTableWidgetItem()
            memoItem.setData(Qt.DisplayRole, memo)
            if obj['shoziflag'] == True:
                    maru = '○'
            else:
                    maru = ''
            self.table.setItem(i, 0, titleItem)
            self.table.setItem(i, 1, QTableWidgetItem(obj['isbn']))
            self.table.setItem(i, 2, QTableWidgetItem(obj['dokuryodate']))
            self.table.setItem(i, 3, QTableWidgetItem(obj['memo']))
            self.table.setItem(i, 4, QTableWidgetItem(maru))
            i += 1
        #table.resize(150, 50)
        #self.table.resizeColumnToContents(0)
        self.table.horizontalHeader().setStretchLastSection(True)

        self.table.doubleClicked.connect(self.tableclick)
        mainLayout.addWidget(self.table, 6, 1)
        #mainLayout.addWidget(topFiller)

        self.setLayout(mainLayout)
        self.setWindowTitle("Simple Book Log")
        #self.csvImport()
        self.loadFromFile('./a.bl')


    def createUI(self):
        self.setWindowTitle('Equipment Manager 0.3')
        #Menu Bar
        fileMenuBar = QMenuBar(self)
        menuFile = QMenu(fileMenuBar)
        actionChangePath = QAction(tr("Change Path"), self)
        fileMenuBar.addMenu(menuFile)
        menuFile.addAction(actionChangePath)



    def addContact(self):
        self.oldTitle = self.titleLine.text()
        self.oldMemo = self.memoText.toPlainText()
        self.oldIsbn = self.isbnLine.text()

        self.titleLine.clear()
        self.memoText.clear()
        self.isbnLine.clear()

        self.updateInterface(self.AddingMode)

    def editContact(self):
        self.oldTitle = self.titleLine.text()
        self.oldMemo = self.memoText.toPlainText()
        self.oldDokuryodate = self.dokuryodate.text()
        self.oldIsbn = self.isbnLine.text()
        self.oldShoziflag = self.shoziflag.isChecked()

        self.updateInterface(self.EditingMode)

    def submitContact(self):
        title = self.titleLine.text()
        memo = self.memoText.toPlainText()
        isbn = self.isbnLine.text()
        dokuryodate = self.dokuryodate.text()
        shoziflag = self.shoziflag.isChecked()

        if title == "" or memo == "":
            QMessageBox.information(self, "Empty Field",
                    "Please enter a title and memo.")
            return

        if self.currentMode == self.AddingMode:
            if title not in self.contacts:
                self.contacts[title] = {'memo':memo, 'dokuryodate':dokuryodate, 'isbn':isbn, 'shoziflag':shoziflag}
                QMessageBox.information(self, "追加しました",
                        "\"%s\" は追加されました。" % title)
            else:
                QMessageBox.information(self, "追加できませんでした",
                        "\"%s\" はすでに存在しています。" % title)
                return

        elif self.currentMode == self.EditingMode:
            if self.oldTitle != title:
                if title not in self.contacts:
                    QMessageBox.information(self, "編集しました",
                            "\"%s\" は編集されました。" % self.oldTitle)
                    del self.contacts[self.oldTitle]
                    self.contacts[title] = memo
                else:
                    QMessageBox.information(self, "編集できませんでした。",
                            "\"%s\"はすでに存在しています。" % title)
                    return
            elif self.oldMemo != memo:
                QMessageBox.information(self, "編集しました",
                        "\"%s\"は編集されました。" % title)
                self.contacts[title] = {memo:memo, dokuryodate:dokuryodate, shoziflag:shoziflag, isbn:isbn }

        self.updateInterface(self.NavigationMode)
    # ボタンの処理
    def cancel(self):
        self.titleLine.setText(self.oldTitle)
        self.memoText.setText(self.oldMemo)
        self.dokuryodate.setDate(self.oldDokuryodate)
        self.shoziflag.setChecked(self.oldShoziflag)
        self.isbnLine.setText(self.oldIsbn)
        self.updateInterface(self.NavigationMode)

    def removeContact(self):
        title = self.titleLine.text()
        memo = self.memoText.toPlainText()

        if title in self.contacts:
            button = QMessageBox.question(self, "Confirm Remove",
                    "Are you sure you want to remove \"%s\"?" % title,
                    QMessageBox.Yes | QMessageBox.No)

            if button == QMessageBox.Yes:
                self.previous()
                del self.contacts[title]

                QMessageBox.information(self, "Remove Successful",
                        "\"%s\" has been removed from your memo book." % title)

        self.updateInterface(self.NavigationMode)

    def next(self):
        title = self.titleLine.text()
        it = iter(self.contacts)

        try:
            while True:
                this_title, _ = it.next()

                if this_title == title:
                    next_title, next_memo, next_date = it.next()
                    break
        except StopIteration:
            next_title, next_memo = iter(self.contacts).next()

        self.titleLine.setText(next_title)
        self.memoText.setText(next_memo)

    def previous(self):
        title = self.titleLine.text()

        prev_title = prev_memo = None
        for this_title, this_memo in self.contacts:
            if this_title == title:
                break

            prev_title = this_title
            prev_memo = this_memo
        else:
            self.titleLine.clear()
            self.memoText.clear()
            return

        if prev_title is None:
            for prev_title, prev_memo in self.contacts:
                pass

        self.titleLine.setText(prev_title)
        self.memoText.setText(prev_memo)

    def Contact(self):
        self.dialog.show()

        if self.dialog.exec_() == QDialog.Accepted:
            contactTitle = self.dialog.getFindText()

            found = False
            for this_title, this_memo in self.contacts:
            #    if contactTitle in this_title:
                if re.search(contactTitle, this_title):
                    found = True
                    break



            if found:
                self.titleLine.setText(this_title)
                self.memoText.setText(self.contacts[this_title])
                self.isbnLine.setText(self.contacts[this_title])
                self.dokuryodate.setDate(self.contacts[this_title])
                self.shoziflag.setChecked(self.contacts[this_title])
            else:
                QMessageBox.information(self, "Contact Not Found",
                        "Sorry, \"%s\" is not in your address book." % contactTitle)
                return

        self.updateInterface(self.NavigationMode)
 # ボタンを押せるか押せないかの処理
    def updateInterface(self, mode):
        self.currentMode = mode

        if self.currentMode in (self.AddingMode, self.EditingMode):
            self.titleLine.setReadOnly(False)
            self.titleLine.setFocus(Qt.OtherFocusReason)
            self.isbnLine.setReadOnly(False)
            self.dokuryodate.setReadOnly(False)
            self.memoText.setReadOnly(False)

            self.addButton.setEnabled(False)
            self.editButton.setEnabled(False)
            self.removeButton.setEnabled(False)

            self.nextButton.setEnabled(False)
            self.previousButton.setEnabled(False)

            self.submitButton.show()
            self.cancelButton.show()

            self.loadButton.setEnabled(False)
            self.saveButton.setEnabled(False)
            self.exportButton.setEnabled(False)

        elif self.currentMode == self.NavigationMode:
            if not self.contacts:
                self.titleLine.clear()
                self.memoText.clear()
                self.dokuryodate.clear()
                self.isbnLine.clear()

            self.titleLine.setReadOnly(True)
            self.memoText.setReadOnly(True)
            self.dokuryodate.setReadOnly(True)
            self.shoziflag
            self.isbnLine.setReadOnly(True)
            self.addButton.setEnabled(True)

            number = len(self.contacts)
            self.editButton.setEnabled(number >= 1)
            self.removeButton.setEnabled(number >= 1)
            self.findButton.setEnabled(number > 2)
            self.nextButton.setEnabled(number > 1)
            self.previousButton.setEnabled(number >1 )

            self.submitButton.hide()
            self.cancelButton.hide()

            self.exportButton.setEnabled(number >= 1)

            self.loadButton.setEnabled(True)
            self.saveButton.setEnabled(number >= 1)
            #テーブルの更新
            i = 0
            for title, obj in self.contacts.items():
                titleItem = QTableWidgetItem(title)
                memoItem = QTableWidgetItem()
                memoItem.setData(Qt.DisplayRole, obj['memo'])
                if obj['shoziflag'] == True:
                    maru = '○'
                else:
                    maru = ''

                self.table.setItem(i, 0, titleItem)
                self.table.setItem(i, 1, QTableWidgetItem(obj['isbn']))
                self.table.setItem(i, 2, QTableWidgetItem(obj['dokuryodate']))
                self.table.setItem(i, 3, QTableWidgetItem(obj['memo']))
                self.table.setItem(i, 4, QTableWidgetItem(maru))

                i += 1


    def saveToFile(self):
        fileTitle, _ = QFileDialog.getSaveFileName(self, "Save book log",
                '', "Book Log (*.bl);;All Files (*)")

        if not fileTitle:
            return

        try:
            out_file = open(str(fileTitle), 'wb')
        except IOError:
            QMessageBox.information(self, "Unable to open file",
                    "There was an error opening \"%s\"" % fileTitle)
            return
        pickle.dump(self.contacts, out_file)
        out_file.close()

    def loadFromFile(self, fileName= None):


        if not fileName:
            fileName, _ = QFileDialog.getOpenFileName(self, "Open Address Book",
                '', "Address Book (*.bl);;All Files (*)")

        try:
            in_file = open(str(fileName), 'rb')
        except IOError:
            QMessageBox.information(self, "Unable to open file",
                    "There was an error opening \"%s\"" % fileName)
            return

        self.contacts = pickle.load(in_file)
        in_file.close()

        if len(self.contacts) == 0:
            QMessageBox.information(self, "No contacts in file",
                    "The file you are attempting to open contains no "
                    "contacts.")
        else:
            for title, obj in self.contacts:
                date = QDate.fromString(obj['dokuryodate'])
                self.titleLine.setText(title)
                self.memoText.setText(obj['memo'])
                self.shoziflag.setChecked(obj['shoziflag'])
                self.isbnLine.setText(obj['isbn'])
                self.dokuryodate.setDate(date)

        self.updateInterface(self.NavigationMode)

    def exportAsVCard(self):
        title = str(self.titleLine.text())
        memo = self.memoText.toPlainText()

        titleList = title.split()

        if len(titleList) > 1:
            firstName = nameList[0]
            lastName = nameList[-1]
        else:
            firstName = name
            lastName = ''

        fileName, _ = QFileDialog.getSaveFileName(self, "Export Contact", '',
                "vCard Files (*.vcf);;All Files (*)")

        if not fileName:
            return

        out_file = QFile(fileName)

        if not out_file.open(QIODevice.WriteOnly):
            QMessageBox.information(self, "Unable to open file",
                    out_file.errorString())
            return

        out_s = QTextStream(out_file)

        out_s << 'BEGIN:VCARD' << '\n'
        out_s << 'VERSION:2.1' << '\n'
        out_s << 'N:' << lastName << ';' << firstName << '\n'
        out_s << 'FN:' << ' '.join(nameList) << '\n'

        address.replace(';', '\\;')
        address.replace('\n', ';')
        address.replace(',', ' ')

        out_s << 'ADR;HOME:;' << address << '\n'
        out_s << 'END:VCARD' << '\n'

        QMessageBox.information(self, "Export Successful",
                "\"%s\" has been exported as a vCard." % name)
    def csvImport(self):
        with open('MediaMarkerExport.csv', newline='', encoding='utf-8') as f:
            reader = csv.reader(f)
            for r in reader:
                if r[2] == 1:
                    flag = True
                else:
                    flag = False
                self.contacts[r[0]] = {'isbn':r[1], 'dokuryodate':r[3].replace('-', '/'), 'shoziflag':flag, 'memo':''}
        aa = 0


    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        #self.fileMenu.addAction(self.newAct)
        #self.fileMenu.addAction(self.openAct)
        #self.fileMenu.addAction(self.saveAct)
        #self.fileMenu.addAction(self.printAct)
        #self.fileMenu.addSeparator()
        #self.fileMenu.addAction(self.exitAct)

        self.editMenu = self.menuBar().addMenu("&Edit")
        self.editMenu.addAction(self.undoAct)
        self.editMenu.addAction(self.redoAct)
        self.editMenu.addSeparator()
        self.editMenu.addAction(self.cutAct)
        self.editMenu.addAction(self.copyAct)
        self.editMenu.addAction(self.pasteAct)
        self.editMenu.addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)
        self.helpMenu.addAction(self.aboutQtAct)

        self.formatMenu = self.editMenu.addMenu("&Format")
        self.formatMenu.addAction(self.boldAct)
        self.formatMenu.addAction(self.italicAct)
        self.formatMenu.addSeparator().setText("Alignment")
        self.formatMenu.addAction(self.leftAlignAct)
        self.formatMenu.addAction(self.rightAlignAct)
        self.formatMenu.addAction(self.justifyAct)
        self.formatMenu.addAction(self.centerAct)
        self.formatMenu.addSeparator()
        self.formatMenu.addAction(self.setLineSpacingAct)
        self.formatMenu.addAction(self.setParagraphSpacingAct)

    def tableclick(self, mi):
        row = mi.row()
        column = mi.column()
        #QMessageBox.information(self, "Export Successful",
        #        "%d x %d" % (row, column))
        title = self.titleLine.text()
        it = iter(self.contacts)

        try:
            n = 0
            while True:

                next_title, next_obj = it.next()
                if row == n:

                    break
                n += 1
        except StopIteration:
            next_title, next_obj = iter(self.contacts).next()

        self.titleLine.setText(next_title)
        self.memoText.setText(next_obj['memo'])
        self.isbnLine.setText(next_obj['isbn'])
        self.dokuryodate.setDate(next_obj['dokuryodate'])
        self.shoziflag.setChecked(next_obj['shoziflag'])
Ejemplo n.º 51
0
class DataWidget(QWidget):

    def __init__(self):
        super(DataWidget, self).__init__(None)
        self.read_data_file(config.HISTORIC_DATA)
        self.start_date = date(2016, 10, 1)
        self.end_date = date(2016, 11, 1)
        self.graph = GraphCanvas(self.data_frame)
        with open(config.LOGFILE, 'w', newline='') as logfile:
            logwriter = csv.writer(logfile)
            logwriter.writerow(config.headers)

        # options group box
        self.optionsGroupBox = QGroupBox("Options")
        options_layout = QVBoxLayout()
        date_range_layout = QFormLayout()
        start_date_label = QLabel("Start Date:")
        self.start_date_box = QDateEdit(self.start_date)
        self.start_date_box.setCalendarPopup(True)
        self.start_date_box.setDisplayFormat(config.DATE_DISPLAY_FORMAT)
        self.start_date_box.dateChanged.connect(self.plot)
        end_date_label = QLabel("End Date:")
        self.end_date_box = QDateEdit(self.end_date)
        self.end_date_box.setCalendarPopup(True)
        self.end_date_box.setDisplayFormat(config.DATE_DISPLAY_FORMAT)
        self.end_date_box.dateChanged.connect(self.plot)
        date_range_layout.addRow(start_date_label, self.start_date_box)
        date_range_layout.addRow(end_date_label, self.end_date_box)
        # days of week
        self.sundayCheckBox = QCheckBox("Sunday")
        self.mondayCheckBox = QCheckBox("Monday")
        self.tuesdayCheckBox = QCheckBox("Tuesday")
        self.wednesdayCheckBox = QCheckBox("Wednesday")
        self.thursdayCheckBox = QCheckBox("Thursday")
        self.fridayCheckBox = QCheckBox("Friday")
        self.saturdayCheckBox = QCheckBox("Saturday")
        self.sundayCheckBox.toggled.connect(self.plot)
        self.mondayCheckBox.toggled.connect(self.plot)
        self.tuesdayCheckBox.toggled.connect(self.plot)
        self.wednesdayCheckBox.toggled.connect(self.plot)
        self.thursdayCheckBox.toggled.connect(self.plot)
        self.fridayCheckBox.toggled.connect(self.plot)
        self.saturdayCheckBox.toggled.connect(self.plot)

        options_layout.addLayout(date_range_layout)
        options_layout.addWidget(self.sundayCheckBox)
        options_layout.addWidget(self.mondayCheckBox)
        options_layout.addWidget(self.tuesdayCheckBox)
        options_layout.addWidget(self.wednesdayCheckBox)
        options_layout.addWidget(self.thursdayCheckBox)
        options_layout.addWidget(self.fridayCheckBox)
        options_layout.addWidget(self.saturdayCheckBox)
        options_layout.addWidget(QPushButton("Button"))
        self.optionsGroupBox.setLayout(options_layout)

        # graph group box
        self.graphGroupBox = QGroupBox("Graph")
        graphLayout = QVBoxLayout()
        graphLayout.addWidget(self.graph)
        self.graphGroupBox.setLayout(graphLayout)

        # choice group box
        self.choiceGroupBox = QGroupBox("Choice")

        choice_layout = QVBoxLayout()

        choice_layout_1 = QHBoxLayout()
        choice_layout_1.addWidget(QLabel("A"))
        choice_layout_1.addWidget(QLabel("B"))
        choice_layout_1.addWidget(QLabel("C"))
        choice_layout_1.addWidget(QLabel("D"))

        choice_layout_2 = QHBoxLayout()
        self.decision_value_1 = QSpinBox()
        self.decision_value_2 = QSpinBox()
        self.decision_value_3 = QSpinBox()
        self.decision_value_4 = QSpinBox()
        choice_layout_2.addWidget(self.decision_value_1)
        choice_layout_2.addWidget(self.decision_value_2)
        choice_layout_2.addWidget(self.decision_value_3)
        choice_layout_2.addWidget(self.decision_value_4)

        choice_layout.addLayout(choice_layout_1)
        choice_layout.addLayout(choice_layout_2)

        self.decision_value_1.setValue(42)

        self.choiceGroupBox.setLayout(choice_layout)

        # count-down timer
        self.timerGroupBox = QGroupBox("Timer")
        timer_layout = QVBoxLayout()
        self.timerGroupBox.setLayout(timer_layout)
        self.count_down_timer = CountDownTimer()
        timer_layout.addWidget(self.count_down_timer.lcd)

        # central widget
        frame = QFrame(self)
        self.grid = QGridLayout(frame)
        self.grid.setSpacing(16)
        self.grid.setContentsMargins(16, 16, 16, 16)
        self.grid.addWidget(self.optionsGroupBox, 0, 0, 2, 1)
        self.grid.addWidget(self.graphGroupBox, 0, 1, 2, 1)
        self.grid.addWidget(self.timerGroupBox, 0, 2)
        self.grid.addWidget(self.choiceGroupBox, 2, 1)
        self.grid.setColumnStretch(0, 2)
        self.grid.setColumnStretch(1, 6)
        self.grid.setColumnStretch(2, 1)
        self.grid.setRowStretch(0, 1)
        self.grid.setRowStretch(1, 2)
        self.grid.setRowStretch(2, 2)
        self.setLayout(self.grid)

    def read_data_file(self, data_file):
        """read data_file and import it's content as pandas dataframe"""
        dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d')
        self.data_frame = pd.read_csv(data_file,
                                      index_col=0,
                                      parse_dates=True)

    def plot(self):
        """
        Method to update start / end dates upon selection. Fetch the start /
        end dates, convert the QTime datatype to DateTime.Date datatype, and
        plot the graph.
        """
        self.start_date = self.start_date_box.date().toPyDate()
        self.end_date = self.end_date_box.date().toPyDate()
        self.graph.plot(self.data_frame.loc[self.start_date : self.end_date])

    def add_log_row(self):
        """
        Write data in the log file
        :return:
        """
        new_row = [config.id, config.age, config.male, config.field,
                   'test_condition', datetime.now()]
        with open(config.LOGFILE, 'a', newline='') as logfile:
            logwriter = csv.writer(logfile)
            logwriter.writerow(new_row)
Ejemplo n.º 52
0
    def __init__(self, parent=None):
        super(BookLog, self).__init__(parent)

        self.contacts = SortedDict()
        self.oldTitle = ''
        self.oldMemo = ''
        self.oldShoziflag = False
        self.oldIsbn = ''
        self.oldDokuryodate = QDate()
        self.currentMode = self.NavigationMode

        #ラベル
        titleLabel = QLabel("書名:")
        self.titleLine = QLineEdit()
        self.titleLine.setReadOnly(True)

        dokuryoLabel = QLabel("読了日:")
        self.dokuryodate = QDateEdit()
        self.dokuryodate.setReadOnly(True)


        memoLabel = QLabel("メモ:")
        self.memoText = QTextEdit()
        self.memoText.setReadOnly(True)

        isbnLabel = QLabel("ISBN:")
        self.isbnLine = QLineEdit()
        self.isbnLine.setReadOnly(True)

        shoziflag = QLabel("所持:")
        self.shoziflag = QCheckBox()

        self.addButton = QPushButton("&追加")
        self.addButton.show()
        self.editButton = QPushButton("&編集")
        self.editButton.setEnabled(False)
        self.removeButton = QPushButton("&削除")
        self.removeButton.setEnabled(False)
        self.findButton = QPushButton("&検索")
        self.findButton.setEnabled(False)
        self.submitButton = QPushButton("&挿入")
        self.submitButton.hide()
        self.cancelButton = QPushButton("&キャンセル")
        self.cancelButton.hide()

        self.nextButton = QPushButton("&次")
        self.nextButton.setEnabled(False)
        self.previousButton = QPushButton("&前")
        self.previousButton.setEnabled(False)

        self.loadButton = QPushButton("&Load...")
        self.loadButton.setToolTip("Load contacts from a file")
        self.saveButton = QPushButton("Sa&ve...")
        self.saveButton.setToolTip("Save contacts to a file")
        self.saveButton.setEnabled(False)

        self.exportButton = QPushButton("Ex&port")
        self.exportButton.setToolTip("Export as vCard")
        self.exportButton.setEnabled(False)

        self.dialog = FindDialog()

        self.addButton.clicked.connect(self.addContact)
        self.submitButton.clicked.connect(self.submitContact)
        self.editButton.clicked.connect(self.editContact)
        self.removeButton.clicked.connect(self.removeContact)
        #self.findButton.clicked.connect(self.findContact)
        self.cancelButton.clicked.connect(self.cancel)
        self.nextButton.clicked.connect(self.next)
        self.previousButton.clicked.connect(self.previous)
        self.loadButton.clicked.connect(self.loadFromFile)
        self.saveButton.clicked.connect(self.saveToFile)
        self.exportButton.clicked.connect(self.exportAsVCard)

        #self.createMenus()
        #topFiller = QWidget()
        #topFiller.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        buttonLayout1 = QVBoxLayout()
        buttonLayout1.addWidget(self.addButton)
        buttonLayout1.addWidget(self.editButton)
        buttonLayout1.addWidget(self.removeButton)
        buttonLayout1.addWidget(self.findButton)
        buttonLayout1.addWidget(self.submitButton)
        buttonLayout1.addWidget(self.cancelButton)
        buttonLayout1.addWidget(self.loadButton)
        buttonLayout1.addWidget(self.saveButton)
        buttonLayout1.addWidget(self.exportButton)
        buttonLayout1.addStretch()

        buttonLayout2 = QHBoxLayout()
        buttonLayout2.addWidget(self.previousButton)
        buttonLayout2.addWidget(self.nextButton)

        mainLayout = QGridLayout()
        mainLayout.addWidget(titleLabel, 0, 0)
        mainLayout.addWidget(self.titleLine, 0, 1)
        mainLayout.addWidget(memoLabel, 3, 0, Qt.AlignTop)
        mainLayout.addWidget(self.memoText, 3, 1)
        mainLayout.addWidget(dokuryoLabel, 2, 0)
        mainLayout.addWidget(self.dokuryodate, 2, 1)
        mainLayout.addWidget(isbnLabel, 1, 0)
        mainLayout.addWidget(self.isbnLine, 1, 1)
        mainLayout.addWidget(shoziflag, 4, 0)
        mainLayout.addWidget(self.shoziflag, 4, 1)
        mainLayout.addLayout(buttonLayout1, 6, 2)
        mainLayout.addLayout(buttonLayout2, 5, 1)
        #テーブル

        self.table = QTableWidget(100, 5,)
        self.table.setHorizontalHeaderLabels(["書名", "ISBN", "読了日", "メモ", "所持"])
        self.table.verticalHeader().setVisible(False)
        #for i, (title, memo) in enumerate(tableData):

        i = 0
        for title, obj in self.contacts.items():
            titleItem = QTableWidgetItem(title)
            memoItem = QTableWidgetItem()
            memoItem.setData(Qt.DisplayRole, memo)
            if obj['shoziflag'] == True:
                    maru = '○'
            else:
                    maru = ''
            self.table.setItem(i, 0, titleItem)
            self.table.setItem(i, 1, QTableWidgetItem(obj['isbn']))
            self.table.setItem(i, 2, QTableWidgetItem(obj['dokuryodate']))
            self.table.setItem(i, 3, QTableWidgetItem(obj['memo']))
            self.table.setItem(i, 4, QTableWidgetItem(maru))
            i += 1
        #table.resize(150, 50)
        #self.table.resizeColumnToContents(0)
        self.table.horizontalHeader().setStretchLastSection(True)

        self.table.doubleClicked.connect(self.tableclick)
        mainLayout.addWidget(self.table, 6, 1)
        #mainLayout.addWidget(topFiller)

        self.setLayout(mainLayout)
        self.setWindowTitle("Simple Book Log")
        #self.csvImport()
        self.loadFromFile('./a.bl')
Ejemplo n.º 53
0
 def text(self, *args, **kwargs):
     vDate = QDateEdit.text(self, *args, **kwargs)
     [day, month, year] = vDate.split('/')
     vDate = "{}-{}-{}".format(year, month, day)
     return vDate
Ejemplo n.º 54
0
class SeriesDialog(QDialog):
	"A window for adding/modifying series"

	series_queue = queue.Queue()
	SERIES = pyqtSignal(list)
	SERIES_EDIT = pyqtSignal(list, int)
	#series_list = [] # might want to extend this to allow mass series adding

	def _init__(self, parent=None):
		super().__init__()
	#TODO: Implement a way to mass add series'
	#IDEA: Extend dialog in a ScrollArea with more forms...

	def initUI(self):
		main_layout = QVBoxLayout()

		f_web = QGroupBox("From the Web")
		f_web.setCheckable(False)
		main_layout.addWidget(f_web)
		web_layout = QHBoxLayout()
		f_web.setLayout(web_layout)

		f_local = QGroupBox("From local folder")
		f_local.setCheckable(False)
		main_layout.addWidget(f_local)
		local_layout = QHBoxLayout()
		f_local.setLayout(local_layout)

		f_series = QGroupBox("Series Info")
		f_series.setCheckable(False)
		main_layout.addWidget(f_series)
		series_layout = QFormLayout()
		f_series.setLayout(series_layout)

		def basic_web(name):
			return QLabel(name), QLineEdit(), QPushButton("Fetch")

		exh_lbl, exh_edit, exh_btn = basic_web("ExHentai:")
		web_layout.addWidget(exh_lbl, 0, Qt.AlignLeft)
		web_layout.addWidget(exh_edit, 0)
		web_layout.addWidget(exh_btn, 0, Qt.AlignRight)

		choose_folder = QPushButton("Choose Folder")
		choose_folder.clicked.connect(self.choose_dir)
		local_layout.addWidget(choose_folder, Qt.AlignLeft)

		self.title_edit = QLineEdit()
		self.title_edit.setFocus()
		self.author_edit = QLineEdit()
		self.descr_edit = QTextEdit()
		self.descr_edit.setFixedHeight(70)
		self.descr_edit.setPlaceholderText("HTML 4 tags are supported")
		self.lang_box = QComboBox()
		self.lang_box.addItems(["English", "Japanese", "Other"])
		self.lang_box.setCurrentIndex(0)
		self.tags_edit = QLineEdit()
		self.tags_edit.setPlaceholderText("namespace1:tag1, tag2, namespace3:tag3, etc..")
		self.type_box = QComboBox()
		self.type_box.addItems(["Manga", "Doujinshi", "Other"])
		self.type_box.setCurrentIndex(0)
		#self.type_box.currentIndexChanged[int].connect(self.doujin_show)
		#self.doujin_parent = QLineEdit()
		#self.doujin_parent.setVisible(False)
		self.status_box = QComboBox()
		self.status_box.addItems(["Unknown", "Ongoing", "Completed"])
		self.status_box.setCurrentIndex(0)
		self.pub_edit = QDateEdit()
		self.pub_edit.setCalendarPopup(True)
		self.pub_edit.setDate(QDate.currentDate())
		self.path_lbl = QLabel("unspecified...")
		self.path_lbl.setWordWrap(True)

		series_layout.addRow("Title:", self.title_edit)
		series_layout.addRow("Author:", self.author_edit)
		series_layout.addRow("Description:", self.descr_edit)
		series_layout.addRow("Language:", self.lang_box)
		series_layout.addRow("Tags:", self.tags_edit)
		series_layout.addRow("Type:", self.type_box)
		series_layout.addRow("Publication Date:", self.pub_edit)
		series_layout.addRow("Path:", self.path_lbl)

		final_buttons = QHBoxLayout()
		final_buttons.setAlignment(Qt.AlignRight)
		main_layout.addLayout(final_buttons)
		done = QPushButton("Done")
		done.setDefault(True)
		done.clicked.connect(self.accept)
		cancel = QPushButton("Cancel")
		cancel.clicked.connect(self.reject)
		final_buttons.addWidget(cancel)
		final_buttons.addWidget(done)


		self.setLayout(main_layout)

	# TODO: complete this... maybe another time.. 
	#def doujin_show(self, index):
	#	if index is 1:
	#		self.doujin_parent.setVisible(True)
	#	else:
	#		self.doujin_parent.setVisible(False)

	def choose_dir(self):
		dir_name = QFileDialog.getExistingDirectory(self, 'Choose a folder')
		head, tail = os.path.split(dir_name)
		self.title_edit.setText(tail)
		self.path_lbl.setText(dir_name)

	def check(self):
		if len(self.title_edit.text()) is 0:
			self.title_edit.setFocus()
			self.title_edit.setStyleSheet("border-style:outset;border-width:2px;border-color:red;")
			return False
		elif len(self.author_edit.text()) is 0:
			self.author_edit.setText("Anon")

		if len(self.descr_edit.toPlainText()) is 0:
			self.descr_edit.setText("<i>No description..</i>")

		#if self.path_lbl.text() == "unspecified...":
		#	return False

		return True

	def accept(self):
		from ..database import seriesdb

		def do_chapters(series):
			thread = threading.Thread(target=self.set_chapters, args=(series,))
			thread.start()
			thread.join()
			return self.series_queue.get()

		if self.check():
			new_series = seriesdb.Series()
			new_series.title = self.title_edit.text()
			new_series.artist = self.author_edit.text()
			new_series.path = self.path_lbl.text()
			new_series.info = self.descr_edit.toPlainText()
			new_series.type = self.type_box.currentText()
			new_series.language = self.lang_box.currentText()
			new_series.status = self.status_box.currentText()
			qpub_d = self.pub_edit.date().toString("ddMMyyyy")
			dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date()
			new_series.pub_date = dpub_d

			updated_series = do_chapters(new_series)
			#for ser in self.series:
			self.SERIES.emit([updated_series])
			super().accept()

	def set_chapters(self, series_object):
		path = series_object.path
		con = os.listdir(path) # list all folders in series dir
		chapters = sorted([os.path.join(path,sub) for sub in con if os.path.isdir(os.path.join(path, sub))]) #subfolders
		# if series has chapters divided into sub folders
		if len(chapters) != 0:
			for numb, ch in enumerate(chapters):
				chap_path = os.path.join(path, ch)
				series_object.chapters[numb] = chap_path

		else: #else assume that all images are in series folder
			series_object.chapters[0] = path
				
		#find last edited file
		times = set()
		for root, dirs, files in os.walk(path, topdown=False):
			for img in files:
				fp = os.path.join(root, img)
				times.add( os.path.getmtime(fp) )
		series_object.last_update = time.asctime(time.gmtime(max(times)))
		self.series_queue.put(series_object)
		return True

	def reject(self):
		if self.check():
			msgbox = QMessageBox()
			msgbox.setText("<font color='red'><b>Noo oniichan! You were about to add a new series.</b></font>")
			msgbox.setInformativeText("Do you really want to discard?")
			msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
			msgbox.setDefaultButton(QMessageBox.No)
			if msgbox.exec() == QMessageBox.Yes:
				super().reject()
		else:
			super().reject()

	def trigger(self, list_of_index=None):
		if not list_of_index:
			self.initUI()
		else:
			assert isinstance(list_of_index, list)
			self.position = list_of_index[0].row()
			for index in list_of_index:
				series = index.data(Qt.UserRole+1)
				self.setSeries(series)

		from ..constants import WINDOW as parent
		self.resize(500,200)
		frect = self.frameGeometry()
		frect.moveCenter(QDesktopWidget().availableGeometry().center())
		self.move(frect.topLeft()-QPoint(0,120))
		self.setAttribute(Qt.WA_DeleteOnClose)
		self.setWindowFlags(Qt.FramelessWindowHint)
		self.exec()


	def setSeries(self, series):
		"To be used for when editing a series"
		self.series = series
		main_layout = QVBoxLayout()

		f_web = QGroupBox("Fetch metadata from Web")
		f_web.setCheckable(False)
		main_layout.addWidget(f_web)
		web_layout = QHBoxLayout()
		f_web.setLayout(web_layout)

		f_series = QGroupBox("Series Info")
		f_series.setCheckable(False)
		main_layout.addWidget(f_series)
		series_layout = QFormLayout()
		f_series.setLayout(series_layout)

		def basic_web(name):
			return QLabel(name), QLineEdit(), QPushButton("Fetch")

		exh_lbl, exh_edit, exh_btn = basic_web("ExHentai:")
		web_layout.addWidget(exh_lbl, 0, Qt.AlignLeft)
		web_layout.addWidget(exh_edit, 0)
		web_layout.addWidget(exh_btn, 0, Qt.AlignRight)

		self.title_edit = QLineEdit()
		self.title_edit.setText(series.title)
		self.author_edit = QLineEdit()
		self.author_edit.setText(series.artist)
		self.descr_edit = QTextEdit()
		self.descr_edit.setText(series.info)
		self.descr_edit.setAcceptRichText(True)
		self.descr_edit.setFixedHeight(70)
		self.lang_box = QComboBox()
		self.lang_box.addItems(["English", "Japanese", "Other"])
		if series.language is "English":
			self.lang_box.setCurrentIndex(0)
		elif series.language is "Japanese":
			self.lang_box.setCurrentIndex(1)
		else:
			self.lang_box.setCurrentIndex(2)

		self.tags_edit = QLineEdit() #TODO Finish this..
		self.tags_edit.setPlaceholderText("namespace1:tag1, tag2, namespace3:tag3, etc..")
		self.type_box = QComboBox()
		self.type_box.addItems(["Manga", "Doujinshi", "Other"])
		if series.type is "Manga":
			self.type_box.setCurrentIndex(0)
		elif series.type is "Doujinshi":
			self.type_box.setCurrentIndex(1)
		else:
			self.type_box.setCurrentIndex(2)
		#self.type_box.currentIndexChanged[int].connect(self.doujin_show)
		#self.doujin_parent = QLineEdit()
		#self.doujin_parent.setVisible(False)
		self.status_box = QComboBox()
		self.status_box.addItems(["Unknown", "Ongoing", "Completed"])
		if series.status is "Ongoing":
			self.status_box.setCurrentIndex(1)
		elif series.status is "Completed":
			self.status_box.setCurrentIndex(2)
		else:
			self.status_box.setCurrentIndex(0)

		self.pub_edit = QDateEdit() # TODO: Finish this..
		self.pub_edit.setCalendarPopup(True)
		series_pub_date = "{}".format(series.pub_date)
		qdate_pub_date = QDate.fromString(series_pub_date, "yyyy-MM-dd")
		self.pub_edit.setDate(qdate_pub_date)
		self.path_lbl = QLabel("unspecified...")
		self.path_lbl.setWordWrap(True)
		self.path_lbl.setText(series.path)

		series_layout.addRow("Title:", self.title_edit)
		series_layout.addRow("Author:", self.author_edit)
		series_layout.addRow("Description:", self.descr_edit)
		series_layout.addRow("Language:", self.lang_box)
		series_layout.addRow("Tags:", self.tags_edit)
		series_layout.addRow("Type:", self.type_box)
		series_layout.addRow("Publication Date:", self.pub_edit)
		series_layout.addRow("Path:", self.path_lbl)

		final_buttons = QHBoxLayout()
		final_buttons.setAlignment(Qt.AlignRight)
		main_layout.addLayout(final_buttons)
		done = QPushButton("Done")
		done.setDefault(True)
		done.clicked.connect(self.accept_edit)
		cancel = QPushButton("Cancel")
		cancel.clicked.connect(self.reject_edit)
		final_buttons.addWidget(cancel)
		final_buttons.addWidget(done)

		self.setLayout(main_layout)

	def accept_edit(self):

		if self.check():
			new_series = self.series
			new_series.title = self.title_edit.text()
			new_series.artist = self.author_edit.text()
			new_series.path = self.path_lbl.text()
			new_series.info = self.descr_edit.toPlainText()
			new_series.type = self.type_box.currentText()
			new_series.language = self.lang_box.currentText()
			new_series.status = self.status_box.currentText()
			qpub_d = self.pub_edit.date().toString("ddMMyyyy")
			dpub_d = datetime.strptime(qpub_d, "%d%m%Y").date()
			new_series.pub_date = dpub_d

			#for ser in self.series:
			self.SERIES_EDIT.emit([new_series], self.position)
			super().accept()

	def reject_edit(self):
		super().reject()