Exemple #1
0
class IPFSHashExplorerToolBox(GalacteekTab):
    """
    Organizes IPFSHashExplorerWidgets with a QToolBox
    """
    def __init__(self, gWindow, hashRef, maxItems=16, parent=None):
        super(IPFSHashExplorerToolBox, self).__init__(gWindow)

        self.rootHash = hashRef
        self.maxItems = maxItems

        self.toolbox = QToolBox()
        self.exLayout = QVBoxLayout()
        self.exLayout.addWidget(self.toolbox)

        self.vLayout.addLayout(self.exLayout)
        if self.rootHash:
            self.viewHash(self.rootHash)

    @property
    def itemsCount(self):
        return self.toolbox.count()

    def viewHash(self, hashRef, addClose=False, autoOpenFolders=False):
        w = self.lookup(hashRef)
        if w:
            self.toolbox.setCurrentWidget(w)
            return True

        if self.itemsCount > self.maxItems:
            return False

        view = IPFSHashExplorerWidget(hashRef,
                                      parent=self,
                                      addClose=addClose,
                                      autoOpenFolders=autoOpenFolders)
        view.closeRequest.connect(functools.partial(self.remove, view))
        view.directoryOpenRequest.connect(
            lambda cid: self.viewHash(cid, addClose=True))

        idx = self.toolbox.addItem(view, getIconIpfsWhite(), hashRef)
        self.toolbox.setCurrentIndex(idx)
        view.reFocus()
        return True

    def lookup(self, hashRef):
        for idx in range(self.itemsCount):
            if self.toolbox.itemText(idx) == hashRef:
                return self.toolbox.widget(idx)

    def remove(self, view):
        idx = self.toolbox.indexOf(view)
        if idx:
            self.toolbox.removeItem(idx)
            # Always display previous index in the stack
            if self.itemsCount > 0:
                rIdx = idx - 1
                view = self.toolbox.widget(rIdx)
                if view:
                    self.toolbox.setCurrentWidget(view)
                    view.reFocus()
def set_combobox_index(combo_box: QtWidgets.QToolBox):
    try:
        if (int(configs.load_state_value(combo_box.objectName(), INDEX)) <
                combo_box.count()):
            combo_box.setCurrentIndex(
                int(configs.load_state_value(combo_box.objectName(), INDEX)))
    except ValueError:
        configs.save_state_value(combo_box.objectName(), INDEX,
                                 str(combo_box.currentIndex()))
class UITlvInfo(QGroupBox):
    __codecinfo_ = None
    __sdpinfo_ = None
    __fileinfo_ = None

    def __init__(self, title: str):
        super(UITlvInfo, self).__init__(title)
        self.__initUI()

    def __initUI(self):
        vlayout = QVBoxLayout(self)
        self.__toolBox_ = QToolBox()
        vlayout.addWidget(self.__toolBox_)

        #  设置左侧导航栏 toolBox 初始化时的宽度
        self.__toolBox_.setStyleSheet("QToolBoxButton { min-width:180px}")
        # 设置左侧导航栏 toolBox 在左右拉拽时的最小宽度
        self.__toolBox_.setMinimumWidth(100)
        # 设置软件启动时默认打开导航栏的第几个 Item;这里设置的是打开第1个 Item。
        self.__toolBox_.setCurrentIndex(0)
        # self.__toolBox_.setFrameShape(QToolBox.Shape.StyledPanel) # 为toolbox增加边框
        # self.__toolBox_.set

        self.setFileInfoText(info)
        self.setTlvSdpText(sdp)
        self.setTlvCodecText('')

    def setFileInfoText(self, text: str):
        if self.__fileinfo_ is None:
            self.__fileinfo_ = QTextBrowser()
            self.__toolBox_.addItem(self.__fileinfo_, "File Info")

        self.__fileinfo_.setText(text)

    def setTlvSdpText(self, text):
        if self.__sdpinfo_ is None:
            self.__sdpinfo_ = QTextBrowser()
            self.__toolBox_.addItem(self.__sdpinfo_, 'Sdp Info')

        self.__sdpinfo_.setText(text)

    def setTlvCodecText(self, text):
        if self.__codecinfo_ is None:
            self.__codecinfo_ = QTextBrowser()
            self.__toolBox_.addItem(self.__codecinfo_, 'Codec Info')

        self.__codecinfo_.setText(text)
Exemple #4
0
    def __init__(self):
        super(MainForm, self).__init__()

        # 主窗口初始化时实现主窗口布局
        self.setupUi(self)

        toolBox = QToolBox()

        #  设置左侧导航栏 toolBox 初始化时的宽度
        toolBox.setStyleSheet("QToolBoxButton { min-width:210px}")

        # 设置左侧导航栏 toolBox 在左右拉拽时的最小宽度
        toolBox.setMinimumWidth(100)

        toolBox.addItem(QPushButton("Tab Content 1"), "Tab &1")
        toolBox.addItem(QLabel("Tab Content 2"), "生产动态分析测试与建模")
        toolBox.addItem(QPlainTextEdit('Text 3'), QIcon('snapshot.png'), "设置")
        toolBox.setCurrentIndex(0)  # 设置软件启动时默认打开导航栏的第几个 Item;这里设置的是打开第1个 Item。
        self.verticalLayout.addWidget(toolBox)

        # #  下面两行为设置 QSplitter 分割器伸缩大小因子,但是这样设置全屏后导航栏放大了不好看
        # self.splitter.setStretchFactor(0, 30)  # 分割器左边第1个占比例30%
        # self.splitter.setStretchFactor(1, 70)  # 分割器左边第1个占比例70%

        #  下面一行为设置 QSplitter 分割器伸缩大小因子,但是这样设置全屏后导航栏放大了比较好看;不清楚原因。
        self.splitter.setStretchFactor(
            0, 0
        )  # 此函数用于设定:控件是否可伸缩。第一个参数用于指定控件的序号。第二个函数大于0时,表示控件可伸缩,小于0时,表示控件不可伸缩。
        self.splitter.setStretchFactor(
            1, 1
        )  # 此函数用于设定:控件是否可伸缩。第一个参数用于指定控件的序号。第二个函数大于0时,表示控件可伸缩,小于0时,表示控件不可伸缩。

        #  设置 QSplitter 分割器各部分最小化时的情况,设置为“False”意味着左右拉动分隔栏时各部分不会消失;此设置也可以在界面设计时在 QtDesigner 里设置。
        self.splitter.setChildrenCollapsible(False)

        #  设置 QSplitter 分割器随主窗口自适应大小变化。此设置也可以在界面设计时在 QtDesigner 里设置。
        self.splitter.setAutoFillBackground(True)

        # 主窗口初始化时实例化子窗口
        self.child = ChildrenForm()

        # 在主窗口的QSplitter里添加子窗口
        self.splitter.addWidget(self.child)
Exemple #5
0
class QuickInsert(QWidget):
    def __init__(self, dockwidget):
        super(QuickInsert, self).__init__(dockwidget)
        self._dockwidget = weakref.ref(dockwidget)
        # filled in by ButtonGroup subclasses
        self.actionDict = {}

        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)

        self.helpButton = QToolButton(
            icon=icons.get("help-contents"),
            autoRaise=True,
            clicked=lambda: userguide.show("quickinsert"))
        self.directionLabel = QLabel()
        self.direction = QComboBox()
        self.direction.addItems(['', '', ''])
        self.direction.setItemIcon(0, icons.get("go-up"))
        self.direction.setItemIcon(2, icons.get("go-down"))
        self.direction.setCurrentIndex(1)
        hor = QHBoxLayout()
        hor.setContentsMargins(0, 0, 0, 0)
        hor.addWidget(self.helpButton)
        hor.addWidget(self.directionLabel)
        hor.addWidget(self.direction)
        layout.addLayout(hor)

        self.toolbox = QToolBox(self)
        gadgets.toolboxwheeler.ToolBoxWheeler(self.toolbox)
        layout.addWidget(self.toolbox)

        for cls in (
                articulations.Articulations,
                dynamics.Dynamics,
                spanners.Spanners,
                barlines.BarLines,
        ):
            widget = cls(self)
            self.toolbox.addItem(widget, widget.icon(), '')

        app.translateUI(self)
        userguide.openWhatsThis(self)

        # restore remembered current page
        name = QSettings().value("quickinsert/current_tool", "", str)
        if name:
            for i in range(self.toolbox.count()):
                if name == self.toolbox.widget(i).__class__.__name__.lower():
                    self.toolbox.setCurrentIndex(i)
                    break
        self.toolbox.currentChanged.connect(self.slotCurrentChanged)

    def slotCurrentChanged(self, index):
        name = self.toolbox.widget(index).__class__.__name__.lower()
        QSettings().setValue("quickinsert/current_tool", name)

    def translateUI(self):
        self.setWhatsThis(
            _("<p>With the Quick Insert Panel you can add various music "
              "elements to the current note or selected music.</p>\n"
              "<p>See {link} for more information.</p>").format(
                  link=userguide.util.format_link("quickinsert")))
        self.helpButton.setToolTip(_("Help"))
        self.directionLabel.setText(_("Direction:"))
        for item, text in enumerate((_("Up"), _("Neutral"), _("Down"))):
            self.direction.setItemText(item, text)
        for i in range(self.toolbox.count()):
            self.toolbox.setItemText(i, self.toolbox.widget(i).title())
            self.toolbox.setItemToolTip(i, self.toolbox.widget(i).tooltip())

    def actionForName(self, name):
        """This is called by the ShortcutCollection of our dockwidget, e.g. if the user presses a key."""
        try:
            return self.actionDict[name]
        except KeyError:
            pass

    def dockwidget(self):
        return self._dockwidget()
    def initUI(self):
        StoryTypeGroupBox = QGroupBox()
        StoryTypeLayer = FlowLayout()
        for key in WdStoryType.keys():
            widget = QCheckBox(WdStoryType[key][1] if WdStoryType[key][1] != "" else WdStoryType[key][0])
            widget.setObjectName("WdStoryType." + str(key))
            widget.setCheckState(WdStoryType[key][2])
            widget.setEnabled(widget.checkState() != 1)
            widget.setMinimumWidth(230)
            StoryTypeLayer.addWidget(widget)
            self.StoryTypeList.append(widget)
        StoryTypeGroupBox.setLayout(StoryTypeLayer)

        InlineShapeTypeGroupBox = QGroupBox()
        InlineShapeTypeLayer = FlowLayout()
        for key in WdInlineShapeType.keys():
            widget = QCheckBox(
                WdInlineShapeType[key][1] if WdInlineShapeType[key][1] != "" else WdInlineShapeType[key][0]
            )
            widget.setObjectName("WdInlineShapeType." + str(key))
            widget.setCheckState(WdInlineShapeType[key][2])
            widget.setEnabled(widget.checkState() != 1)
            widget.setMinimumWidth(230)
            InlineShapeTypeLayer.addWidget(widget)
            self.InlineShapeList.append(widget)
        InlineShapeTypeGroupBox.setLayout(InlineShapeTypeLayer)

        ShapeTypeGroupBox = QGroupBox()
        ShapeTypeLayer = FlowLayout()
        for key in MsoShapeType.keys():
            widget = QCheckBox(MsoShapeType[key][1] if MsoShapeType[key][1] != "" else MsoShapeType[key][0])
            widget.setObjectName("MsoShapeType." + str(key))
            widget.setCheckState(MsoShapeType[key][2])
            widget.setEnabled(widget.checkState() != 1)
            widget.setMinimumWidth(230)
            ShapeTypeLayer.addWidget(widget)
            self.ShapeTypeList.append(widget)
        ShapeTypeGroupBox.setLayout(ShapeTypeLayer)

        """TabWidget=QTabWidget()
        TabWidget.addTab(StoryTypeGroupBox,"StoryType")
        TabWidget.addTab(InlineShapeTypeGroupBox,"InlineShapeType")
        TabWidget.addTab(ShapeTypeGroupBox,"ShapeType")
        TabWidget.setCurrentIndex(0)"""
        TabWidget = QToolBox()
        TabWidget.addItem(StoryTypeGroupBox, "StoryType")
        TabWidget.addItem(InlineShapeTypeGroupBox, "InlineShapeType")
        TabWidget.addItem(ShapeTypeGroupBox, "ShapeType")
        TabWidget.setCurrentIndex(0)

        hbox = QVBoxLayout()
        hbox.addWidget(TabWidget)

        btnGrp = QDialogButtonBox()
        btnClose = QPushButton("Закрыть")
        # btnApply=QPushButton("Применить")
        btnGrp.addButton(btnClose, QDialogButtonBox.ActionRole)
        # btnGrp.addButton(btnApply,QDialogButtonBox.ActionRole)
        hbox.addWidget(btnGrp)

        btnClose.clicked.connect(self.close)
        # btnApply.clicked.connect(self.apply)
        self.apply()
        self.setLayout(hbox)
        self.setGeometry(500, 100, 500, 400)
        self.setWindowTitle("Опции")
        self.setWindowFlags(Qt.Dialog | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint)
Exemple #7
0
class QuickInsert(QWidget):
    def __init__(self, dockwidget):
        super(QuickInsert, self).__init__(dockwidget)
        self._dockwidget = weakref.ref(dockwidget)
        # filled in by ButtonGroup subclasses
        self.actionDict = {}
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)
        
        self.helpButton = QToolButton(
            icon = icons.get("help-contents"),
            autoRaise = True,
            clicked = lambda: userguide.show("quickinsert"))
        self.directionLabel = QLabel()
        self.direction = QComboBox()
        self.direction.addItems(['', '', ''])
        self.direction.setItemIcon(0, icons.get("go-up"))
        self.direction.setItemIcon(2, icons.get("go-down"))
        self.direction.setCurrentIndex(1)
        hor = QHBoxLayout()
        hor.setContentsMargins(0, 0, 0, 0)
        hor.addWidget(self.helpButton)
        hor.addWidget(self.directionLabel)
        hor.addWidget(self.direction)
        layout.addLayout(hor)
        
        self.toolbox = QToolBox(self)
        gadgets.toolboxwheeler.ToolBoxWheeler(self.toolbox)
        layout.addWidget(self.toolbox)
        
        for cls in (
                articulations.Articulations,
                dynamics.Dynamics,
                spanners.Spanners,
                barlines.BarLines,
            ):
            widget = cls(self)
            self.toolbox.addItem(widget, widget.icon(), '')
        
        app.translateUI(self)
        userguide.openWhatsThis(self)
        
        # restore remembered current page
        name = QSettings().value("quickinsert/current_tool", "", str)
        if name:
            for i in range(self.toolbox.count()):
                if name == self.toolbox.widget(i).__class__.__name__.lower():
                    self.toolbox.setCurrentIndex(i)
                    break
        self.toolbox.currentChanged.connect(self.slotCurrentChanged)
        
    def slotCurrentChanged(self, index):
        name = self.toolbox.widget(index).__class__.__name__.lower()
        QSettings().setValue("quickinsert/current_tool", name)
    
    def translateUI(self):
        self.setWhatsThis(_(
            "<p>With the Quick Insert Panel you can add various music "
            "elements to the current note or selected music.</p>\n"
            "<p>See {link} for more information.</p>").format(link=
                userguide.util.format_link("quickinsert")))
        self.helpButton.setToolTip(_("Help"))
        self.directionLabel.setText(_("Direction:"))
        for item, text in enumerate((_("Up"), _("Neutral"), _("Down"))):
            self.direction.setItemText(item, text)
        for i in range(self.toolbox.count()):
            self.toolbox.setItemText(i, self.toolbox.widget(i).title())
            self.toolbox.setItemToolTip(i, self.toolbox.widget(i).tooltip())
            
    def actionForName(self, name):
        """This is called by the ShortcutCollection of our dockwidget, e.g. if the user presses a key."""
        try:
            return self.actionDict[name]
        except KeyError:
            pass

    def dockwidget(self):
        return self._dockwidget()
Exemple #8
0
    def setupWindow(self):
        """The window is comprised of two main parts: A Q3DBars graph on the left, and QToolBox
        on the right containing different widgets for tweaking different settings in the Q3DBars graph."""
        header_label = QLabel(
            "Comparison of Average Monthly Temperatures of Select U.S. Cities 1990-2000 (˚C)"
        )
        header_label.setAlignment(Qt.AlignCenter)

        # Load and prepare the data for the three datasets
        data_files = [
            "LasVegas_temp.csv", "Spokane_temp.csv", "Richmond_temp.csv"
        ]
        temperature_data = {}
        # Create a dictionary with key, value pairs pertaining to each city and dataset
        for f in data_files:
            data_name = f.split(
                "_")[0] + "_data"  # Create a dictionary key for each city
            data = self.loadCSVFile("files/" + f)

            # Select 11 years: 1990-2000; the first column in each file is the years
            rows, columns = data.shape
            self.years = data[:, 0]
            monthly_temps = data[:, 1:columns].astype(float)
            temperature_data[data_name] = monthly_temps

        bar_graph = Q3DBars()  # Create instance for bar graph
        bar_graph.setMultiSeriesUniform(
            True)  # Bars are scaled proportionately
        bar_graph.scene().activeCamera().setCameraPreset(
            Q3DCamera.CameraPresetFront)

        # Create lists of QBarDataItem objects for each city
        vegas_data_items = []
        for row in temperature_data["LasVegas_data"]:
            vegas_data_items.append([QBarDataItem(value) for value in row])

        spokane_data_items = []
        for row in temperature_data["Spokane_data"]:
            spokane_data_items.append([QBarDataItem(value) for value in row])

        richmond_data_items = []
        for row in temperature_data["Richmond_data"]:
            richmond_data_items.append([QBarDataItem(value) for value in row])

        self.months = [
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December"
        ]

        # Create instances of QBar3DSeries for each set of data; dataProxy() handles
        # modifying data in the series
        vegas_series = QBar3DSeries()
        vegas_series.dataProxy().addRows(vegas_data_items)
        vegas_series.dataProxy().setRowLabels(self.years)  # rowLabel
        vegas_series.dataProxy().setColumnLabels(self.months)  # colLabel

        spokane_series = QBar3DSeries()
        spokane_series.dataProxy().addRows(spokane_data_items)

        richmond_series = QBar3DSeries()
        richmond_series.dataProxy().addRows(richmond_data_items)

        # Create the valueLabel
        temperature_axis = QValue3DAxis()
        temperature_axis.setRange(-10, 40)
        temperature_axis.setLabelFormat(u"%.1f \N{degree sign}C")
        bar_graph.setValueAxis(temperature_axis)

        # Set the format for the labels that appear when items are clicked on
        vegas_series.setItemLabelFormat(
            "LasVegas - @colLabel @rowLabel: @valueLabel")
        spokane_series.setItemLabelFormat(
            "Spokane - @colLabel @rowLabel: @valueLabel")
        richmond_series.setItemLabelFormat(
            "Richmond - @colLabel @rowLabel: @valueLabel")

        # Add the three series to the bar graph
        bar_graph.setPrimarySeries(vegas_series)
        bar_graph.addSeries(spokane_series)
        bar_graph.addSeries(richmond_series)

        # Create a QWidget to hold only the graph
        graph_container = QWidget.createWindowContainer(bar_graph)
        main_h_box = QHBoxLayout()  # Main layout for the entire window
        graph_v_box = QVBoxLayout()  # Layout that holds the graph
        graph_v_box.addWidget(header_label)
        graph_v_box.addWidget(graph_container, 1)

        ##############################################################################
        # The following section creates the QToolBox that appears on the
        # right of the window and contains widgets for interacting with the graph
        self.modifier = GraphModifier(self,
                                      bar_graph)  # Create modifier instance

        settings_toolbox = QToolBox()
        settings_toolbox.setFixedWidth(300)
        settings_toolbox.setCurrentIndex(0)  # Show the first tab

        # The first tab - Widgets for rotating the bar graph and changing the camera
        horizontal_rotation_slider = QSlider(Qt.Horizontal)
        horizontal_rotation_slider.setTickInterval(20)
        horizontal_rotation_slider.setRange(-180, 180)
        horizontal_rotation_slider.setValue(0)
        horizontal_rotation_slider.setTickPosition(QSlider.TicksBelow)
        horizontal_rotation_slider.valueChanged.connect(
            self.modifier.rotateHorizontal)

        vertical_rotation_slider = QSlider(Qt.Horizontal)
        vertical_rotation_slider.setTickInterval(20)
        vertical_rotation_slider.setRange(-180, 180)
        vertical_rotation_slider.setValue(0)
        vertical_rotation_slider.setTickPosition(QSlider.TicksBelow)
        vertical_rotation_slider.valueChanged.connect(
            self.modifier.rotateVertical)

        # QPushButton for changing the camera's view point
        camera_view_button = QPushButton("Change Camera View")
        camera_view_button.clicked.connect(self.modifier.changeCameraView)

        # Layout for the View tab (first tab)
        view_tab_container = QWidget()
        view_tab_v_box = QVBoxLayout()
        view_tab_v_box.setAlignment(Qt.AlignTop)
        view_tab_v_box.addWidget(QLabel("Rotate Horizontally"))
        view_tab_v_box.addWidget(horizontal_rotation_slider)
        view_tab_v_box.addWidget(QLabel("Rotate Vertically"))
        view_tab_v_box.addWidget(vertical_rotation_slider)
        view_tab_v_box.addWidget(camera_view_button)
        view_tab_container.setLayout(view_tab_v_box)

        settings_toolbox.addItem(view_tab_container, "View")

        # The second tab - Widgets for changing the appearance of the graph. Recheck the
        # background and grid checkboxes if the theme has changed
        show_background_cb = QCheckBox("Show Background")
        show_background_cb.setChecked(True)
        show_background_cb.stateChanged.connect(
            self.modifier.showOrHideBackground)
        self.modifier.background_selected.connect(
            show_background_cb.setChecked)

        show_grid_cb = QCheckBox("Show Grid")
        show_grid_cb.setChecked(True)
        show_grid_cb.stateChanged.connect(self.modifier.showOrHideGrid)
        self.modifier.grid_selected.connect(show_grid_cb.setChecked)

        smooth_bars_cb = QCheckBox("Smoothen Bars")
        smooth_bars_cb.stateChanged.connect(self.modifier.smoothenBars)

        # QComboBox for selecting the Qt theme
        themes = [
            "Qt", "Primary Colors", "Digia", "Stone Moss", "Army Blue",
            "Retro", "Ebony", "Isabelle"
        ]
        select_theme_combo = QComboBox()
        select_theme_combo.addItems(themes)
        select_theme_combo.setCurrentIndex(0)
        select_theme_combo.currentIndexChanged.connect(
            self.modifier.changeTheme)

        # QComboBox for selecting the visual style of the bars
        bar_style_combo = QComboBox()
        bar_style_combo.addItem("Bar", QAbstract3DSeries.MeshBar)
        bar_style_combo.addItem("Pyramid", QAbstract3DSeries.MeshPyramid)
        bar_style_combo.addItem("Cylinder", QAbstract3DSeries.MeshCylinder)
        bar_style_combo.addItem("Sphere", QAbstract3DSeries.MeshSphere)
        bar_style_combo.setCurrentIndex(0)
        bar_style_combo.currentIndexChanged.connect(
            self.modifier.changeBarStyle)

        # Layout for the Style tab (second tab)
        style_tab_container = QWidget()
        style_tab_v_box = QVBoxLayout()
        style_tab_v_box.setAlignment(Qt.AlignTop)
        style_tab_v_box.addWidget(show_background_cb)
        style_tab_v_box.addWidget(show_grid_cb)
        style_tab_v_box.addWidget(smooth_bars_cb)
        style_tab_v_box.addWidget(QLabel("Select Qt Theme"))
        style_tab_v_box.addWidget(select_theme_combo)
        style_tab_v_box.addWidget(QLabel("Select Bar Style"))
        style_tab_v_box.addWidget(bar_style_combo)
        style_tab_container.setLayout(style_tab_v_box)

        settings_toolbox.addItem(style_tab_container, "Style")

        # The third tab - Widgets for hiding/showing different series and changing how
        # items are viewed and selected
        second_series_cb = QCheckBox("Show Second Series")
        second_series_cb.setChecked(True)
        second_series_cb.stateChanged.connect(self.modifier.showOrHideSeries)

        third_series_cb = QCheckBox("Show Third Series")
        third_series_cb.setChecked(True)
        third_series_cb.stateChanged.connect(self.modifier.showOrHideSeries)

        # QComboBox for changing how items in the bar graph are selected
        selection_mode_combo = QComboBox()
        selection_mode_combo.addItem("None", QAbstract3DGraph.SelectionNone)
        selection_mode_combo.addItem("Bar", QAbstract3DGraph.SelectionItem)
        selection_mode_combo.addItem("Row", QAbstract3DGraph.SelectionRow)
        selection_mode_combo.addItem("Column",
                                     QAbstract3DGraph.SelectionColumn)
        selection_mode_combo.addItem(
            "Item, Row, Column", QAbstract3DGraph.SelectionItemRowAndColumn)
        selection_mode_combo.setCurrentIndex(1)
        selection_mode_combo.currentIndexChanged.connect(
            self.modifier.changeSelectionStyle)

        # QComboBox for selecting which years to view
        select_year_combo = QComboBox()
        select_year_combo.addItems(self.years)
        select_year_combo.addItem("All Years")
        select_year_combo.setCurrentIndex(len(self.years))
        select_year_combo.currentIndexChanged.connect(
            self.modifier.selectYears)

        # QComboBox for selecting which months to view
        select_month_combo = QComboBox()
        select_month_combo.addItems(self.months)
        select_month_combo.addItem("All Months")
        select_month_combo.setCurrentIndex(len(self.months))
        select_month_combo.currentIndexChanged.connect(
            self.modifier.selectMonths)

        # Layout for the Selection tab (third tab)
        selection_tab_container = QWidget()
        selection_tab_v_box = QVBoxLayout()
        selection_tab_v_box.addWidget(second_series_cb)
        selection_tab_v_box.addWidget(third_series_cb)
        selection_tab_v_box.addWidget(QLabel("Choose Selection Mode"))
        selection_tab_v_box.addWidget(selection_mode_combo)
        selection_tab_v_box.addWidget(QLabel("Select Year"))
        selection_tab_v_box.addWidget(select_year_combo)
        selection_tab_v_box.addWidget(QLabel("Select Month"))
        selection_tab_v_box.addWidget(select_month_combo)
        selection_tab_container.setLayout(selection_tab_v_box)

        settings_toolbox.addItem(selection_tab_container, "Selection")

        # Set up the layout for the settings toolbox
        settings_v_box = QVBoxLayout()
        settings_v_box.addWidget(settings_toolbox, 0, Qt.AlignTop)

        main_h_box.addLayout(graph_v_box)
        main_h_box.addLayout(settings_v_box)

        main_widget = QWidget()
        main_widget.setLayout(main_h_box)
        self.setCentralWidget(main_widget)
Exemple #9
0
class TestDialogWind(QDialog):
    def __init__(self, finder, data_for_edit):
        super().__init__()
        self.setWindowTitle('Формирование теста')
        self.resize(SIZE_WIDTH, SIZE_HEIGHT)
        self.list_topics = finder.list_topics_names
        self.list_content = finder.list_topics_data
        self.setStyleSheet('font-size: 16px')
        self.list_models = [None] * len(finder.list_topics_names)

        self.label_name = QLabel()
        self.label_name.setText('Название теста:')
        self.linedit_name = QLineEdit()
        self.layout_name = QHBoxLayout()
        self.layout_name.addWidget(self.label_name)
        self.layout_name.addWidget(self.linedit_name)

        self.check_random = QCheckBox()
        self.check_random.setText('Случайное перемешивание вопросов')
        self.check_study = QCheckBox()
        self.check_study.setText('Обучающий режим теста')
        self.layout_check = QHBoxLayout()
        self.layout_check.addWidget(self.check_random)
        self.layout_check.addWidget(self.check_study)

        self.table = [None] * len(self.list_topics)
        self.tool_box = QToolBox()
        for i in range(len(self.list_topics)):
            self.create_table(i)
            self.table[i] = QTableView(self)
            self.table[i].setModel(self.list_models[i])
            self.table[i].resizeColumnToContents(0)
            self.table[i].setColumnWidth(1, 100)
            self.table[i].setColumnWidth(2, 320)
            self.table[i].setColumnWidth(3, 120)
            self.table[i].setColumnWidth(4, 180)
            self.table[i].setGridStyle(QtCore.Qt.SolidLine)
            self.table[i].resizeRowsToContents()
            self.table[i].setWordWrap(True)
            self.tool_box.addItem(self.table[i], self.list_topics[i][0])
        self.tool_box.setCurrentIndex(0)

        self.button_save = QPushButton()
        self.button_save.setText("Сохранить")
        self.button_save.setDefault(True)
        self.button_save.clicked.connect(self.save_test)
        self.button_cancel = QPushButton()
        self.button_cancel.setText('Отмена')
        self.button_cancel.clicked.connect(self.reject)
        self.layout_button = QHBoxLayout()
        self.layout_button.addWidget(self.button_save)
        self.layout_button.insertSpacing(0, SIZE_WIDTH // 3)
        self.layout_button.addWidget(self.button_cancel)
        self.layout_button.addSpacing(SIZE_WIDTH // 3)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.layout_name)
        self.layout.addLayout(self.layout_check)
        self.layout.addWidget(self.tool_box)
        self.layout.addLayout(self.layout_button)
        self.setLayout(self.layout)
        self.info_challenge = None
        self.the_new_test = not data_for_edit
        if not self.the_new_test:
            self.load_params(data_for_edit)
        self.selected_items = {}

    def load_params(self, data_for_edit):
        self.info_challenge, info_items = data_for_edit
        self.linedit_name.setText(self.info_challenge[1])
        if self.info_challenge[2]:
            self.check_random.setCheckState(QtCore.Qt.Checked)
        if self.info_challenge[3]:
            self.check_study.setCheckState(QtCore.Qt.Checked)
        for i in range(len(self.list_models)):
            name_topic = self.list_topics[i]
            if name_topic[1] not in info_items:
                continue
            classes_for_find = set()
            for elem in info_items[name_topic[1]]:
                classes_for_find.add(elem[0])
            for j in range(self.list_models[i].rowCount()):
                name_class = self.list_models[i].item(j, 0)
                count_items = self.list_models[i].item(j, 1)
                if name_class.text() not in classes_for_find:
                    continue
                name_class.setCheckState(QtCore.Qt.Checked)
                new_count = None
                for elem in info_items[name_topic[1]]:
                    if elem[0] == name_class.text():
                        new_count = elem[1]
                        break
                count_items.setText(str(new_count))

    def create_table(self, index):
        count_rows = len(self.list_content[index])
        self.list_models[index] = QStandardItemModel(0, 5)
        for row in range(count_rows):
            item_name = QStandardItem(self.list_content[index][row])
            item_name.setCheckable(True)
            item_name.setEditable(False)
            item_count = QStandardItem('0')
            item_count.setEnabled(True)
            try:
                exec(f'import {self.list_topics[index][1]} as module')
                test_task = eval(f'module.{self.list_content[index][row]}()')
                test_task.make_task()
                example_text = test_task.generated_text
                answer_text = test_task.calculate_answer(
                    **test_task.values_params)
                image_text = test_task.task_image
            except Exception as e:
                example_text = 'ОШИБКА при генерации задания'
            item_text = QStandardItem(example_text)
            item_text.setEditable(False)
            item_answer = QStandardItem(answer_text)
            item_answer.setEditable(False)
            item_image = QStandardItem(image_text)
            item_image.setEditable(False)
            self.list_models[index].appendRow(
                [item_name, item_count, item_text, item_answer, item_image])

            self.list_models[index].setHorizontalHeaderLabels([
                'Название', 'Количество', 'Пример задания', 'Пример ответа',
                'Изображение'
            ])
        self.list_models[index].itemChanged.connect(self.change_count)

    def change_count(self, item):
        number_row = item.row()
        new_data = item.data(QtCore.Qt.EditRole)
        parent_model = item.model()
        check_field = parent_model.item(number_row, 0)
        count_field = parent_model.item(number_row, 1)
        if item is check_field:
            if check_field.checkState(
            ) == QtCore.Qt.Checked and count_field.data(
                    QtCore.Qt.EditRole) != '0':
                return
            if check_field.checkState(
            ) == QtCore.Qt.Checked and count_field.data(
                    QtCore.Qt.EditRole) == '0':
                count_field.setData('1', QtCore.Qt.EditRole)
                return
            if check_field.checkState(
            ) != QtCore.Qt.Checked and count_field.data(
                    QtCore.Qt.EditRole) != '0':
                count_field.setData('0', QtCore.Qt.EditRole)
                return
        else:
            if check_field.checkState(
            ) != QtCore.Qt.Checked and count_field.data(
                    QtCore.Qt.EditRole) != '0':
                check_field.setCheckState(QtCore.Qt.Checked)
                return
            if check_field.checkState(
            ) == QtCore.Qt.Checked and count_field.data(
                    QtCore.Qt.EditRole) == '0':
                check_field.setCheckState(QtCore.Qt.Unchecked)
                return

    def get_selected_items(self):
        for i in range(len(self.list_models)):
            name_topic = self.list_topics[i]
            for j in range(self.list_models[i].rowCount()):
                name_class = self.list_models[i].item(j, 0)
                count_items = self.list_models[i].item(j, 1)
                if name_class.checkState() == QtCore.Qt.Checked:
                    if name_topic not in self.selected_items:
                        self.selected_items[name_topic] = [
                            (name_class.text(), int(count_items.text()))
                        ]
                    else:
                        self.selected_items[name_topic].append(
                            (name_class.text(), int(count_items.text())))

    def validate(self):
        if len(self.linedit_name.text()) == 0 or self.linedit_name.text(
        ).isspace():
            QMessageBox.warning(
                self, 'Предупреждение',
                'Введите название теста. Это поле не должно быть пустым.')
            return False
        self.get_selected_items()
        if not self.selected_items:
            QMessageBox.warning(
                self, 'Предупреждение',
                'Не выбраны задания теста. Должно быть выбрано хотя бы одно задание.'
            )
            return False
        return True

    def save_test(self):
        id_challenge = None
        if self.validate():
            if not self.the_new_test:
                id_challenge = int(self.info_challenge[0])
                print(id_challenge)
                db = DatabaseEngine()
                res_value = db.delete_items_for_challenge(id_challenge)
                db.close()
                if res_value == -1:
                    return
                db = DatabaseEngine()
                res_value = db.update_challenges('title',
                                                 self.linedit_name.text(),
                                                 id_challenge)
                db.close()
                if res_value == -1:
                    return
                db = DatabaseEngine()
                res_value = db.update_challenges(
                    'mixing', int(self.check_random.isChecked()), id_challenge)
                db.close()
                if res_value == -1:
                    return
                db = DatabaseEngine()
                res_value = db.update_challenges(
                    'training', int(self.check_study.isChecked()),
                    id_challenge)
                db.close()
                if res_value == -1:
                    return
            else:
                db = DatabaseEngine()
                title_challenge = self.linedit_name.text()
                try:
                    db.insert_challenge(title_challenge,
                                        self.check_random.isChecked(),
                                        self.check_study.isChecked())
                except Exception as e:
                    print("Непридвиденная ошибка базы данных", e)
                    return
                id_challenge = db.search_id_challenge(title_challenge)
                db.close()
            if id_challenge is None or id_challenge == -1:
                print("Непридвиденная ошибка базы данных")
                return -1
            db = DatabaseEngine()
            for key, value in self.selected_items.items():
                for elem in value:
                    db.insert_challenge_item(elem[0], id_challenge, elem[1],
                                             key[1])
            db.close()
            if not self.the_new_test:
                QMessageBox().information(self, "Успешно",
                                          'Тест успешно изменен.')
            else:
                QMessageBox().information(self, "Успешно",
                                          'Тест добавлен в базу данных.')
            self.accept()
    def initUI(self):
        StoryTypeGroupBox = QGroupBox()
        StoryTypeLayer = FlowLayout()
        for key in WdStoryType.keys():
            widget = QCheckBox(WdStoryType[key][1] if WdStoryType[key][1] != ""
                               else WdStoryType[key][0])
            widget.setObjectName("WdStoryType." + str(key))
            widget.setCheckState(WdStoryType[key][2])
            widget.setEnabled(widget.checkState() != 1)
            widget.setMinimumWidth(230)
            StoryTypeLayer.addWidget(widget)
            self.StoryTypeList.append(widget)
        StoryTypeGroupBox.setLayout(StoryTypeLayer)

        InlineShapeTypeGroupBox = QGroupBox()
        InlineShapeTypeLayer = FlowLayout()
        for key in WdInlineShapeType.keys():
            widget = QCheckBox(
                WdInlineShapeType[key][1] if WdInlineShapeType[key][1] != ""
                else WdInlineShapeType[key][0])
            widget.setObjectName("WdInlineShapeType." + str(key))
            widget.setCheckState(WdInlineShapeType[key][2])
            widget.setEnabled(widget.checkState() != 1)
            widget.setMinimumWidth(230)
            InlineShapeTypeLayer.addWidget(widget)
            self.InlineShapeList.append(widget)
        InlineShapeTypeGroupBox.setLayout(InlineShapeTypeLayer)

        ShapeTypeGroupBox = QGroupBox()
        ShapeTypeLayer = FlowLayout()
        for key in MsoShapeType.keys():
            widget = QCheckBox(MsoShapeType[key][1] if MsoShapeType[key][1] !=
                               "" else MsoShapeType[key][0])
            widget.setObjectName("MsoShapeType." + str(key))
            widget.setCheckState(MsoShapeType[key][2])
            widget.setEnabled(widget.checkState() != 1)
            widget.setMinimumWidth(230)
            ShapeTypeLayer.addWidget(widget)
            self.ShapeTypeList.append(widget)
        ShapeTypeGroupBox.setLayout(ShapeTypeLayer)
        """TabWidget=QTabWidget()
        TabWidget.addTab(StoryTypeGroupBox,"StoryType")
        TabWidget.addTab(InlineShapeTypeGroupBox,"InlineShapeType")
        TabWidget.addTab(ShapeTypeGroupBox,"ShapeType")
        TabWidget.setCurrentIndex(0)"""
        TabWidget = QToolBox()
        TabWidget.addItem(StoryTypeGroupBox, "StoryType")
        TabWidget.addItem(InlineShapeTypeGroupBox, "InlineShapeType")
        TabWidget.addItem(ShapeTypeGroupBox, "ShapeType")
        TabWidget.setCurrentIndex(0)

        hbox = QVBoxLayout()
        hbox.addWidget(TabWidget)

        btnGrp = QDialogButtonBox()
        btnClose = QPushButton("Закрыть")
        #btnApply=QPushButton("Применить")
        btnGrp.addButton(btnClose, QDialogButtonBox.ActionRole)
        #btnGrp.addButton(btnApply,QDialogButtonBox.ActionRole)
        hbox.addWidget(btnGrp)

        btnClose.clicked.connect(self.close)
        #btnApply.clicked.connect(self.apply)
        self.apply()
        self.setLayout(hbox)
        self.setGeometry(500, 100, 500, 400)
        self.setWindowTitle("Опции")
        self.setWindowFlags(Qt.Dialog | Qt.WindowMinMaxButtonsHint
                            | Qt.WindowCloseButtonHint)