예제 #1
0
    def __init__(self, parent, model, result):
        QWidget.__init__(self, parent)
        self.setLayout(QVBoxLayout())

        scrollArea = QScrollArea(self)
        self.layout().addWidget(scrollArea)
        scrollArea.setWidgetResizable(True)

        viewport = QToolBox()
        scrollArea.setWidget(viewport)

        self.computationTimeGroup = ComputationTimeTable(result)
        self.preemptionsGroup = InformationTable(result, 'preemption_count',
                                                 ['min', 'avg', 'max', 'sum'])
        self.migrationsGroup = InformationTable(result, 'migration_count',
                                                ['min', 'avg', 'max', 'sum'])
        self.taskMigrationsGroup = TaskMigrationTable(result)
        self.responseTimeGroup = InformationTable(
            result,
            'response_time', ['min', 'avg', 'max', 'std dev'],
            map_=lambda x: x / float(model.cycles_per_ms))

        viewport.addItem(self.computationTimeGroup, "Computation time:")
        viewport.addItem(self.preemptionsGroup, "Preemptions:")
        viewport.addItem(self.migrationsGroup, "Migrations:")
        viewport.addItem(self.taskMigrationsGroup, "Task migrations:")
        viewport.addItem(self.responseTimeGroup, "Response time:")
예제 #2
0
    def createLeft(self):
        leftBox = QToolBox()
        leftSys = self.createLeftSys()
        leftBind = self.createLeftBind()
        leftBox.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
        leftBox.addItem(leftSys, "系统信息")
        leftBox.addItem(leftBind, "BIND调整")

        return leftBox
예제 #3
0
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # tool box
        tool_box = QToolBox()

        # items
        tool_box.addItem(QPlainTextEdit('Text 1'), 'Page 1')
        tool_box.addItem(QPlainTextEdit('Text 2'), 'Page 2')

        # vertical box layout
        vlayout = QVBoxLayout()
        vlayout.addWidget(tool_box)
        self.setLayout(vlayout)
예제 #4
0
class LicenseDialog(QDialog, license_dialog.Ui_Dialog):
    accepted = pyqtSignal()
    rejected = pyqtSignal()

    def __init__(self, parent=None, allow_close=False):
        super().__init__(parent)
        self.setupUi(self)

        if parent:
            self.setModal(True)

        if allow_close:
            self.accept_button.hide()
            self.decline_button.hide()
        else:
            self.close_button.hide()

        self.licenses = QToolBox()
        self.lic_layout.addWidget(self.licenses)

        self.__allow_close = allow_close
        self.__accepted = False

        self._init_licenses()

    def _init_licenses(self):
        for lic in self._load_licenses():
            box = QTextEdit()
            box.setReadOnly(True)
            box.setPlainText(lic[1])
            self.licenses.addItem(box, lic[0])

    def _load_licenses(self):
        yield ("fluedit", "All rights reserved")
        yield ("other", "TODO")  # TODO: load licenses

    def on_rejected(self):
        self.rejected.emit()
        self.close()

    def on_accepted(self):
        self.accepted.emit()
        self.__accepted = True
        self.close()

    def closeEvent(self, _ev):
        if not self.__allow_close and not self.__accepted:
            self.rejected.emit()
예제 #5
0
class Window:
    def __init__(self):
        self.__widget = QWidget()
        self.__grid = QGridLayout()
        self.__widget.setLayout(self.__grid)

        self.__label = QLabel(self.__widget)
        self.__label.setText('Enter country name: ')
        self.__grid.addWidget(self.__label, 0, 0)

        self.__entry = QLineEdit(self.__widget)
        self.__entry.setPlaceholderText('Type country...')
        self.__grid.addWidget(self.__entry, 0, 1)

        self.__button = QPushButton(self.__widget)
        self.__button.setText('Search')
        self.__button.clicked.connect(self.__make_request)
        self.__grid.addWidget(self.__button, 0, 2)

        self.__toolbox = QToolBox()
        self.__grid.addWidget(self.__toolbox)

        self.__data_label = QLabel()
        self.__toolbox.addItem(self.__data_label, 'Data:')

        self.__widget.setWindowTitle('Covid App')
        self.__widget.show()

    def __make_request(self):
        if self.__entry.text():
            req = Request("GET", self.__entry.text())
            res = req.get_api()
            if res:
                return self.__set_data(res)
            else:
                return
        else:
            Error('Enter country name')
            self.__data_label.setText("")

    def __set_data(self, data_item):
        if data_item['Country_text'].lower() == 'world':
            Error('Type valid country name')
        else:
            self.__data_label.setText(
                f"Cases: {data_item['Total Cases_text']}\n"
                f"Deaths: {data_item['Total Deaths_text']}\n"
                f"Recovered: {data_item['Total Recovered_text']}")
예제 #6
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()
예제 #7
0
	def makeControlWindow(self):
		tb = QToolBox()
		tb.addItem(self.makeIpContainer(), "Connection and Run-State")
		tb.addItem(self.makeDisplayedParameterControl(), "Displayed Parameters")
		tb.addItem(self.makeSweepControl(), "Sweep Parameters")
		tb.addItem(self.makeCallButtonCtrl(), "Calibration")
		tb.setMinimumWidth(220)
		tb.setMaximumWidth(220)
		layout = QVBoxLayout()
		layout.addWidget(tb)
		layout.addStretch(1)
		return layout
예제 #8
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)
예제 #9
0
def gui_configuration(subwindow,parent):
    
    frame = QFrame()
    layout = QVBoxLayout()
    pushButton1 = QPushButton('Sistemas Lineares')
    

    toolbox = QToolBox()
    label = QLabel('Sistemas de primeira ordem')
    label2= QLabel('Sistemas de segunda ordem')
    toolbox.addItem(label,'Sistemas 1 ordem')
    toolbox.addItem(label2,'Sistemas 2 ordem')
    

    layout.addWidget(pushButton1)
    
    layout.addWidget(toolbox)
    frame.setLayout(layout)
    subwindow.setWidget(frame)
    return subwindow
예제 #10
0
 def makeControlWindow(self):
     tb = QToolBox()
     tb.addItem(self.makeIpContainer(), "Connection and Run-State")
     tb.addItem(self.makeDisplayedParameterControl(),
                "Displayed Parameters")
     tb.addItem(self.makeSweepControl(), "Sweep Parameters")
     tb.addItem(self.makeCallButtonCtrl(), "Calibration")
     tb.setMinimumWidth(220)
     tb.setMaximumWidth(220)
     layout = QVBoxLayout()
     layout.addWidget(tb)
     layout.addStretch(1)
     return layout
예제 #11
0
    def _create_image_processes_boxes(self):
        tool_box = QToolBox()
        for page in TYPES:
            qwidget = QWidget()
            vbox = QVBoxLayout()
            for image_process in self.model.transformations + self.model.splits:
                if image_process.process_type == page:
                    vbox.addWidget(image_process.gui(self.image_widget))

            vbox.addStretch()
            apply_button = QPushButton("Apply")
            apply_button.setToolTip("Apply changes and redraw image")
            apply_button.clicked.connect(self._apply_clicked_handler)
            hbox = QHBoxLayout()
            hbox.addStretch()
            hbox.addWidget(apply_button)
            vbox.addLayout(hbox)
            qwidget.setLayout(vbox)

            tool_box.addItem(qwidget, page[1])
        return tool_box
예제 #12
0
    def init_window(self):

        self.setWindowIcon(QtGui.QIcon(self.iconName))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.setStyleSheet("background-color:orange")

        vbox = QVBoxLayout()

        toolbox = QToolBox()
        toolbox.setStyleSheet("background-color:grey")
        vbox.addWidget(toolbox)

        label = QLabel()
        toolbox.addItem(label, "Python")

        label1 = QLabel()
        toolbox.addItem(label1, "Java")

        label2 = QLabel()
        toolbox.addItem(label2, "C++")

        self.setLayout(vbox)

        self.show()
예제 #13
0
class kstSidebar(QWidget):
    def __init__(self):

        QWidget.__init__(self)

        # Add a toolbox to the sidebar:
        self.toolbox = QToolBox()

        # Each tab of the toolbox contains a widget:
        self.hdfViewerTab = kstHDFViewer()

        # Configure the alignment tab:
        self.preprocessingTab = kstPreprocessingPanel()

        # Configure the refocusing tab:
        self.reconstructionTab = kstReconstructionPanel()

        # Configure the whole widget:
        self.toolbox.addItem(self.hdfViewerTab, KST_SIDEBAR_HDFVIEW)
        self.toolbox.addItem(self.preprocessingTab, KST_SIDEBAR_PREPROC)
        self.toolbox.addItem(self.reconstructionTab, KST_SIDEBAR_RECON)

        # Define layout:
        layout = QVBoxLayout()
        layout.addWidget(self.toolbox)
        layout.setContentsMargins(10, 10, 2, 10)  #left,top,right,bottom
        self.setLayout(layout)
    def initUI(self):
        vbox = QVBoxLayout()

        toolbox = QToolBox()
        toolbox.setStyleSheet('background-color:green')
        toolbox.addItem(QLabel(), "Python")
        toolbox.addItem(QLabel(), "Java")
        toolbox.addItem(QLabel(), "C++")

        vbox.addWidget(toolbox)

        self.setLayout(vbox)
예제 #15
0
    def initUi(self):

        layout = QGridLayout()

        tool_box = QToolBox()

        linux_button = QPushButton('Linux')
        tool_box.addItem(linux_button, 'Linux')

        windows_button = QPushButton('Windows')
        tool_box.addItem(windows_button, 'Windows')

        mac_button = QPushButton('Mac')
        tool_box.addItem(mac_button, 'Mac')

        android_button = QPushButton('Android')
        tool_box.addItem(android_button, 'Android')

        layout.addWidget(tool_box, 0, 0)

        self.setLayout(layout)
예제 #16
0
    def init_ui(self):
        vbox = QVBoxLayout()
        toolbox = QToolBox()
        toolbox.setStyleSheet("background-color:green")
        vbox.addWidget(toolbox)

        label = QLabel()
        toolbox.addItem(label, "Python")

        label = QLabel()
        toolbox.addItem(label, "Java")

        label = QLabel()
        toolbox.addItem(label, "C++")

        self.setLayout(vbox)
예제 #17
0
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)
예제 #18
0
 def InitWindow(self):
     self.setWindowIcon(QtGui.QIcon("icon.png"))
     self.setWindowTitle(self.title)
     self.setGeometry(self.left, self.top, self.width, self.height)
     self.setStyleSheet("background-color:yellow")
     vbox = QVBoxLayout()
     toolbox = QToolBox()
     vbox.addWidget(toolbox)
     label = QLabel()
     toolbox.addItem(label, "Python")
     toolbox.setFont(QtGui.QFont("Sanserif", 15))
     label = QLabel()
     toolbox.addItem(label, "Java")
     label = QLabel()
     toolbox.addItem(label, "C++")
     self.setLayout(vbox)
     self.show()
예제 #19
0
    def InitUI(self):
        vbox = QVBoxLayout()

        toolbox = QToolBox()
        # toolbox.setStyleSheet('background-color:white')
        vbox.addWidget(toolbox)

        label = QLabel()
        toolbox.addItem(label, "Python")

        label = QLabel()
        toolbox.addItem(label, "Java")

        label = QLabel()
        toolbox.addItem(label, "C++")

        self.setLayout(vbox)
예제 #20
0
    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon(self.IconName))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        #self.setStyleSheet('background-color:green')

        vbox = QVBoxLayout()
        toolbox = QToolBox()
        toolbox.setStyleSheet('background-color:green')
        self.label = QLabel()
        self.label2 = QLabel()
        self.label3 = QLabel()

        toolbox.addItem(self.label, "Python")
        toolbox.addItem(self.label2, "Java")
        toolbox.addItem(self.label3, "C++")
        vbox.addWidget(toolbox)

        self.setLayout(vbox)
        self.show()
예제 #21
0
    def add_containers(self, layout):
        
        toolbox = QToolBox()
        toolbox.setMinimumHeight(200)        
        
        linux_button = QPushButton('Linux')
        windows_button = QPushButton('Windows')       
        toolbox.addItem(linux_button, 'Linux')        
        mac_button = QPushButton('Mac')
        
        toolbox.addItem(windows_button, 'Windows')
        toolbox.addItem(mac_button, 'Mac')
        toolbox.setMinimumHeight(200)        
        
        
        tab_widget = QTabWidget()
        tab_widget.insertTab(
                0, QLabel('Linux'), 'Linux')
        tab_widget.insertTab(
                1, QLabel('Windows'), 'Windows')
        tab_widget.insertTab(
                2, QLabel('Mac'), 'Mac')
        tab_widget.setMinimumHeight(200)
        
        plain_text_edit = QPlainTextEdit()
        plain_text_edit.setWordWrapMode(
                QTextOption.NoWrap)

        scroll_area = QScrollArea()
        scroll_area.setWidget(plain_text_edit)
        scroll_area.setWidgetResizable(True)
        scroll_area.setMinimumHeight(200)        

        
        layout.addWidget(toolbox, 0, 1)
        layout.addWidget(tab_widget, 1, 1)
        layout.addWidget(scroll_area, 2, 1)
        
        scroll_area = QScrollArea()
예제 #22
0
class MainWindow(QMainWindow):
    InsertTextButton = 10

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

        self.createActions()
        self.createMenus()
        self.createToolBox()

        self.scene = DiagramScene(self.itemMenu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))
        self.scene.itemInserted.connect(self.itemInserted)
        self.scene.textInserted.connect(self.textInserted)
        self.scene.itemSelected.connect(self.itemSelected)

        self.createToolbars()

        layout = QHBoxLayout()
        layout.addWidget(self.toolBox)
        self.view = QGraphicsView(self.scene)
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("Diagramscene")

    def backgroundButtonGroupClicked(self, button):
        buttons = self.backgroundButtonGroup.buttons()
        for myButton in buttons:
            if myButton != button:
                button.setChecked(False)

        text = button.text()
        if text == "Blue Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background1.png')))
        elif text == "White Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background2.png')))
        elif text == "Gray Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background3.png')))
        else:
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background4.png')))

        self.scene.update()
        self.view.update()

    def buttonGroupClicked(self, id):
        buttons = self.buttonGroup.buttons()
        for button in buttons:
            if self.buttonGroup.button(id) != button:
                button.setChecked(False)

        if id == self.InsertTextButton:
            self.scene.setMode(DiagramScene.InsertText)
        else:
            self.scene.setItemType(id)
            self.scene.setMode(DiagramScene.InsertItem)

    def deleteItem(self):
        for item in self.scene.selectedItems():
            if isinstance(item, DiagramItem):
                item.removeArrows()
            self.scene.removeItem(item)

    def pointerGroupClicked(self, i):
        self.scene.setMode(self.pointerTypeGroup.checkedId())

    def bringToFront(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() >= zValue and isinstance(item, DiagramItem)):
                zValue = item.zValue() + 0.1
        selectedItem.setZValue(zValue)

    def sendToBack(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() <= zValue and isinstance(item, DiagramItem)):
                zValue = item.zValue() - 0.1
        selectedItem.setZValue(zValue)

    def itemInserted(self, item):
        self.pointerTypeGroup.button(DiagramScene.MoveItem).setChecked(True)
        self.scene.setMode(self.pointerTypeGroup.checkedId())
        self.buttonGroup.button(item.diagramType).setChecked(False)

    def textInserted(self, item):
        self.buttonGroup.button(self.InsertTextButton).setChecked(False)
        self.scene.setMode(self.pointerTypeGroup.checkedId())

    def currentFontChanged(self, font):
        self.handleFontChange()

    def fontSizeChanged(self, font):
        self.handleFontChange()

    def sceneScaleChanged(self, scale):
        newScale = scale.left(scale.indexOf("%")).toDouble()[0] / 100.0
        oldMatrix = self.view.matrix()
        self.view.resetMatrix()
        self.view.translate(oldMatrix.dx(), oldMatrix.dy())
        self.view.scale(newScale, newScale)

    def textColorChanged(self):
        self.textAction = self.sender()
        self.fontColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/textpointer.png',
                        QColor(self.textAction.data())))
        self.textButtonTriggered()

    def itemColorChanged(self):
        self.fillAction = self.sender()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon( ':/images/floodfill.png',
                        QColor(self.fillAction.data())))
        self.fillButtonTriggered()

    def lineColorChanged(self):
        self.lineAction = self.sender()
        self.lineColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/linecolor.png',
                        QColor(self.lineAction.data())))
        self.lineButtonTriggered()

    def textButtonTriggered(self):
        self.scene.setTextColor(QColor(self.textAction.data()))

    def fillButtonTriggered(self):
        self.scene.setItemColor(QColor(self.fillAction.data()))

    def lineButtonTriggered(self):
        self.scene.setLineColor(QColor(self.lineAction.data()))

    def handleFontChange(self):
        font = self.fontCombo.currentFont()
        font.setPointSize(self.fontSizeCombo.currentText().toInt()[0])
        if self.boldAction.isChecked():
            font.setWeight(QFont.Bold)
        else:
            font.setWeight(QFont.Normal)
        font.setItalic(self.italicAction.isChecked())
        font.setUnderline(self.underlineAction.isChecked())

        self.scene.setFont(font)

    def itemSelected(self, item):
        font = item.font()
        color = item.defaultTextColor()
        self.fontCombo.setCurrentFont(font)
        self.fontSizeCombo.setEditText(str(font.pointSize()))
        self.boldAction.setChecked(font.weight() == QFont.Bold)
        self.italicAction.setChecked(font.italic())
        self.underlineAction.setChecked(font.underline())

    def about(self):
        QMessageBox.about(self, "About Diagram Scene",
                "The <b>Diagram Scene</b> example shows use of the graphics framework.")

    def createToolBox(self):
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(False)
        self.buttonGroup.buttonClicked[int].connect(self.buttonGroupClicked)

        layout = QGridLayout()
        layout.addWidget(self.createCellWidget("Conditional", DiagramItem.Conditional),
                0, 0)
        layout.addWidget(self.createCellWidget("Process", DiagramItem.Step), 0,
                1)
        layout.addWidget(self.createCellWidget("Input/Output", DiagramItem.Io),
                1, 0)

        textButton = QToolButton()
        textButton.setCheckable(True)
        self.buttonGroup.addButton(textButton, self.InsertTextButton)
        textButton.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30)))
        textButton.setIconSize(QSize(50, 50))

        textLayout = QGridLayout()
        textLayout.addWidget(textButton, 0, 0, Qt.AlignHCenter)
        textLayout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter)
        textWidget = QWidget()
        textWidget.setLayout(textLayout)
        layout.addWidget(textWidget, 1, 1)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        itemWidget = QWidget()
        itemWidget.setLayout(layout)

        self.backgroundButtonGroup = QButtonGroup()
        self.backgroundButtonGroup.buttonClicked.connect(self.backgroundButtonGroupClicked)

        backgroundLayout = QGridLayout()
        backgroundLayout.addWidget(self.createBackgroundCellWidget("Blue Grid",
                ':/images/background1.png'), 0, 0)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("White Grid",
                ':/images/background2.png'), 0, 1)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("Gray Grid",
                ':/images/background3.png'), 1, 0)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("No Grid",
                ':/images/background4.png'), 1, 1)

        backgroundLayout.setRowStretch(2, 10)
        backgroundLayout.setColumnStretch(2, 10)

        backgroundWidget = QWidget()
        backgroundWidget.setLayout(backgroundLayout)

        self.toolBox = QToolBox()
        self.toolBox.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.toolBox.setMinimumWidth(itemWidget.sizeHint().width())
        self.toolBox.addItem(itemWidget, "Basic Flowchart Shapes")
        self.toolBox.addItem(backgroundWidget, "Backgrounds")

    def createActions(self):
        self.toFrontAction = QAction(
                QIcon(':/images/bringtofront.png'), "Bring to &Front",
                self, shortcut="Ctrl+F", statusTip="Bring item to front",
                triggered=self.bringToFront)

        self.sendBackAction = QAction(
                QIcon(':/images/sendtoback.png'), "Send to &Back", self,
                shortcut="Ctrl+B", statusTip="Send item to back",
                triggered=self.sendToBack)

        self.deleteAction = QAction(QIcon(':/images/delete.png'),
                "&Delete", self, shortcut="Delete",
                statusTip="Delete item from diagram",
                triggered=self.deleteItem)

        self.exitAction = QAction("E&xit", self, shortcut="Ctrl+X",
                statusTip="Quit Scenediagram example", triggered=self.close)

        self.boldAction = QAction(QIcon(':/images/bold.png'),
                "Bold", self, checkable=True, shortcut="Ctrl+B",
                triggered=self.handleFontChange)

        self.italicAction = QAction(QIcon(':/images/italic.png'),
                "Italic", self, checkable=True, shortcut="Ctrl+I",
                triggered=self.handleFontChange)

        self.underlineAction = QAction(
                QIcon(':/images/underline.png'), "Underline", self,
                checkable=True, shortcut="Ctrl+U",
                triggered=self.handleFontChange)

        self.aboutAction = QAction("A&bout", self, shortcut="Ctrl+B",
                triggered=self.about)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.exitAction)

        self.itemMenu = self.menuBar().addMenu("&Item")
        self.itemMenu.addAction(self.deleteAction)
        self.itemMenu.addSeparator()
        self.itemMenu.addAction(self.toFrontAction)
        self.itemMenu.addAction(self.sendBackAction)

        self.aboutMenu = self.menuBar().addMenu("&Help")
        self.aboutMenu.addAction(self.aboutAction)

    def createToolbars(self):
        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.deleteAction)
        self.editToolBar.addAction(self.toFrontAction)
        self.editToolBar.addAction(self.sendBackAction)

        self.fontCombo = QFontComboBox()
        self.fontCombo.currentFontChanged.connect(self.currentFontChanged)

        self.fontSizeCombo = QComboBox()
        self.fontSizeCombo.setEditable(True)
        for i in range(8, 30, 2):
            self.fontSizeCombo.addItem(str(i))
        validator = QIntValidator(2, 64, self)
        self.fontSizeCombo.setValidator(validator)
        self.fontSizeCombo.currentIndexChanged.connect(self.fontSizeChanged)

        self.fontColorToolButton = QToolButton()
        self.fontColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fontColorToolButton.setMenu(
                self.createColorMenu(self.textColorChanged, Qt.black))
        self.textAction = self.fontColorToolButton.menu().defaultAction()
        self.fontColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/textpointer.png',
                        Qt.black))
        self.fontColorToolButton.setAutoFillBackground(True)
        self.fontColorToolButton.clicked.connect(self.textButtonTriggered)

        self.fillColorToolButton = QToolButton()
        self.fillColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fillColorToolButton.setMenu(
                self.createColorMenu(self.itemColorChanged, Qt.white))
        self.fillAction = self.fillColorToolButton.menu().defaultAction()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/floodfill.png',
                        Qt.white))
        self.fillColorToolButton.clicked.connect(self.fillButtonTriggered)

        self.lineColorToolButton = QToolButton()
        self.lineColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.lineColorToolButton.setMenu(
                self.createColorMenu(self.lineColorChanged, Qt.black))
        self.lineAction = self.lineColorToolButton.menu().defaultAction()
        self.lineColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/linecolor.png',
                        Qt.black))
        self.lineColorToolButton.clicked.connect(self.lineButtonTriggered)

        self.textToolBar = self.addToolBar("Font")
        self.textToolBar.addWidget(self.fontCombo)
        self.textToolBar.addWidget(self.fontSizeCombo)
        self.textToolBar.addAction(self.boldAction)
        self.textToolBar.addAction(self.italicAction)
        self.textToolBar.addAction(self.underlineAction)

        self.colorToolBar = self.addToolBar("Color")
        self.colorToolBar.addWidget(self.fontColorToolButton)
        self.colorToolBar.addWidget(self.fillColorToolButton)
        self.colorToolBar.addWidget(self.lineColorToolButton)

        pointerButton = QToolButton()
        pointerButton.setCheckable(True)
        pointerButton.setChecked(True)
        pointerButton.setIcon(QIcon(':/images/pointer.png'))
        linePointerButton = QToolButton()
        linePointerButton.setCheckable(True)
        linePointerButton.setIcon(QIcon(':/images/linepointer.png'))

        self.pointerTypeGroup = QButtonGroup()
        self.pointerTypeGroup.addButton(pointerButton, DiagramScene.MoveItem)
        self.pointerTypeGroup.addButton(linePointerButton,
                DiagramScene.InsertLine)
        self.pointerTypeGroup.buttonClicked[int].connect(self.pointerGroupClicked)

        self.sceneScaleCombo = QComboBox()
        self.sceneScaleCombo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.sceneScaleCombo.setCurrentIndex(2)
        self.sceneScaleCombo.currentIndexChanged[str].connect(self.sceneScaleChanged)

        self.pointerToolbar = self.addToolBar("Pointer type")
        self.pointerToolbar.addWidget(pointerButton)
        self.pointerToolbar.addWidget(linePointerButton)
        self.pointerToolbar.addWidget(self.sceneScaleCombo)

    def createBackgroundCellWidget(self, text, image):
        button = QToolButton()
        button.setText(text)
        button.setIcon(QIcon(image))
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.backgroundButtonGroup.addButton(button)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createCellWidget(self, text, diagramType):
        item = DiagramItem(diagramType, self.itemMenu)
        icon = QIcon(item.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, diagramType)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createColorMenu(self, slot, defaultColor):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        colorMenu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.createColorIcon(color), name, self,
                    triggered=slot)
            action.setData(QColor(color)) 
            colorMenu.addAction(action)
            if color == defaultColor:
                colorMenu.setDefaultAction(action)
        return colorMenu

    def createColorToolButtonIcon(self, imageFile, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(imageFile)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    def createColorIcon(self, color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)
예제 #23
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()
예제 #24
0
파일: culled.py 프로젝트: DavidAlt/ITG
class MainWindow(QMainWindow):

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

        self.createActions()
        self.createMenus()
        self.createToolBox()
        self.createStatusBar()
        
        self.scene = ITGScene(self.itemMenu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))
        self.scene.itemInserted.connect(self.itemInserted)
        self.scene.itemSelected.connect(self.itemSelected)
        
        # ================================================================
        #         THIS IS THE PROBLEM SECTION 
        # THIS CAUSES TypeError: native Qt signal is not callable
        # To reproduce the error, run the program, click on one of the 
        # shapes, then click on the scene area
        # ================================================================
        self.scene.selectionChanged.connect(self.print_item_info) # this one doesn't work

        self.createToolbars()

        layout = QHBoxLayout()
        layout.addWidget(self.toolBox)
        self.view = QGraphicsView(self.scene) # view and scene established together
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("ITG: Illegitimate Template Generator")

    #@pyqtSlot() # Adding this does not change the error
    def print_item_info(self):
        for item in self.scene.selectedItems():
            print(item)

    def buttonGroupClicked(self, id):
        buttons = self.buttonGroup.buttons()
        for button in buttons:
            if self.buttonGroup.button(id) != button:
                button.setChecked(False)

        self.scene.setItemType(id)
        self.scene.setMode(ITGScene.InsertItem)
        self.updateStatusBar()
        

    def deleteItem(self):
        for item in self.scene.selectedItems():
            self.scene.removeItem(item)

    def pointerGroupClicked(self, i):
        self.scene.setMode(self.pointerTypeGroup.checkedId())
        self.updateStatusBar()

    def bringToFront(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() >= zValue and isinstance(item, ITGItem)):
                zValue = item.zValue() + 0.1
        selectedItem.setZValue(zValue)

    def sendToBack(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() <= zValue and isinstance(item, ITGItem)):
                zValue = item.zValue() - 0.1
        selectedItem.setZValue(zValue)

    def itemInserted(self, item):
        self.pointerTypeGroup.button(ITGScene.MoveItem).setChecked(True)
        self.scene.setMode(self.pointerTypeGroup.checkedId())
        self.updateStatusBar()
        self.buttonGroup.button(item.ITGType).setChecked(False)

    def sceneScaleChanged(self, scale):
        newScale = scale.left(scale.indexOf("%")).toDouble()[0] / 100.0
        oldMatrix = self.view.matrix()
        self.view.resetMatrix()
        self.view.translate(oldMatrix.dx(), oldMatrix.dy())
        self.view.scale(newScale, newScale)

    def itemColorChanged(self):
        self.fillAction = self.sender()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon( ':/images/floodfill.png',
                        QColor(self.fillAction.data())))
        self.fillButtonTriggered()


    def fillButtonTriggered(self):
        self.scene.setItemColor(QColor(self.fillAction.data()))


    def itemSelected(self, item):
        font = item.font()
        color = item.defaultTextColor()
        self.fontCombo.setCurrentFont(font)
        self.fontSizeCombo.setEditText(str(font.pointSize()))
        self.boldAction.setChecked(font.weight() == QFont.Bold)
        self.italicAction.setChecked(font.italic())
        self.underlineAction.setChecked(font.underline())



    def about(self):
        QMessageBox.about(self, "About ITG Scene",
                "The <b>ITG Scene</b> example shows use of the graphics framework.")

    def createToolBox(self):
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(False)
        self.buttonGroup.buttonClicked[int].connect(self.buttonGroupClicked)

        layout = QGridLayout()
        layout.addWidget(self.createCellWidget("Diamond", ITGItem.Diamond),
                0, 0)
        layout.addWidget(self.createCellWidget("Square", ITGItem.Square), 0,
                1)
        layout.addWidget(self.createCellWidget("Parallelogram", ITGItem.Parallelogram),
                1, 0)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        itemWidget = QWidget()
        itemWidget.setLayout(layout)

        self.backgroundButtonGroup = QButtonGroup()
        
        self.toolBox = QToolBox()
        self.toolBox.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.toolBox.setMinimumWidth(itemWidget.sizeHint().width())
        self.toolBox.addItem(itemWidget, "Basic Components")

    def createActions(self):
        self.toFrontAction = QAction(
                QIcon(':/images/bringtofront.png'), "Bring to &Front",
                self, shortcut="Ctrl+F", statusTip="Bring item to front",
                triggered=self.bringToFront)

        self.sendBackAction = QAction(
                QIcon(':/images/sendtoback.png'), "Send to &Back", self,
                shortcut="Ctrl+B", statusTip="Send item to back",
                triggered=self.sendToBack)

        self.deleteAction = QAction(QIcon(':/images/delete.png'),
                "&Delete", self, shortcut="Delete",
                statusTip="Delete item from ITG",
                triggered=self.deleteItem)

        self.exitAction = QAction("E&xit", self, shortcut="Ctrl+X",
                statusTip="Quit SceneITG example", triggered=self.close)

        self.aboutAction = QAction("A&bout", self, shortcut="Ctrl+B",
                triggered=self.about)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.exitAction)

        self.itemMenu = self.menuBar().addMenu("&Item")
        self.itemMenu.addAction(self.deleteAction)
        self.itemMenu.addSeparator()
        self.itemMenu.addAction(self.toFrontAction)
        self.itemMenu.addAction(self.sendBackAction)

        self.aboutMenu = self.menuBar().addMenu("&Help")
        self.aboutMenu.addAction(self.aboutAction)

    def createToolbars(self):
        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.deleteAction)
        self.editToolBar.addAction(self.toFrontAction)
        self.editToolBar.addAction(self.sendBackAction)

        self.fillColorToolButton = QToolButton()
        self.fillColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fillColorToolButton.setMenu(
                self.createColorMenu(self.itemColorChanged, Qt.red))
        self.fillAction = self.fillColorToolButton.menu().defaultAction()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/floodfill.png',
                        Qt.red))
        self.fillColorToolButton.clicked.connect(self.fillButtonTriggered)

        self.colorToolBar = self.addToolBar("Color")
        self.colorToolBar.addWidget(self.fillColorToolButton)
        

        pointerButton = QToolButton()
        pointerButton.setCheckable(True)
        pointerButton.setChecked(True)
        pointerButton.setIcon(QIcon(':/images/pointer.png'))

        self.pointerTypeGroup = QButtonGroup()
        self.pointerTypeGroup.addButton(pointerButton, ITGScene.MoveItem)
        self.pointerTypeGroup.buttonClicked[int].connect(self.pointerGroupClicked)

        self.sceneScaleCombo = QComboBox()
        self.sceneScaleCombo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.sceneScaleCombo.setCurrentIndex(2)
        self.sceneScaleCombo.currentIndexChanged[str].connect(self.sceneScaleChanged)

        self.pointerToolbar = self.addToolBar("Pointer type")
        self.pointerToolbar.addWidget(pointerButton)
        self.pointerToolbar.addWidget(self.sceneScaleCombo)

    def createBackgroundCellWidget(self, text, image):
        button = QToolButton()
        button.setText(text)
        button.setIcon(QIcon(image))
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.backgroundButtonGroup.addButton(button)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createCellWidget(self, text, ITGType):
        item = ITGItem(ITGType, self.itemMenu)
        icon = QIcon(item.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, ITGType)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createColorMenu(self, slot, defaultColor):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        colorMenu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.createColorIcon(color), name, self,
                    triggered=slot)
            action.setData(QColor(color)) 
            colorMenu.addAction(action)
            if color == defaultColor:
                colorMenu.setDefaultAction(action)
        return colorMenu

    def createColorToolButtonIcon(self, imageFile, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(imageFile)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    def createColorIcon(self, color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)

    def createStatusBar(self):
        self.sbar = self.statusBar()
        
        self.lbl_mode = QLabel('Mode: not set')
        self.sbar.addPermanentWidget(self.lbl_mode)

        self.lbl_selection = QLabel('Sel: none')
        self.sbar.addPermanentWidget(self.lbl_selection)

    def updateStatusBar(self):
        self.lbl_mode.setText('Mode: ' + self.scene.getMode())
        #! This section is not working!!!
        if len(self.scene.selectedItems()) == 0:
            self.lbl_selection.setText('Sel: none')
        elif len(self.scene.selectedItems()) == 1:
            self.lbl_selection.setText('Sel: ' + self.scene.selectedItems()[0].get_ITGType_as_str())
        elif len(self.scene.selectedItems()) > 1:
            self.lbl_selection.setText('Sel: <multiple>')
예제 #25
0
    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)
예제 #26
0
    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)
예제 #27
0
class Form(QWidget):
    def __init__(self):

        super().__init__()

        self.GetItems()
        self.say_altciz = 0
        self.say_italic = 0
        self.say_bold = 0
        self.SetScreen()

    def SetScreen(self):
        self.setWindowTitle("Işılgan Metin Editör")
        self.resize(700, 500)
        sshFile = "style.css"
        with open(sshFile, "r") as fh:

            self.setStyleSheet(fh.read())

        self.spiner.setValue(15)

        self.richText.setFontPointSize(self.spiner.value())

    def GetItems(self):
        layout = QGridLayout()
        #rich
        self.richText = QTextEdit()
        self.richText.textChanged.connect(self.richText_changed)
        self.richText.setStyleSheet("background-color:#7E7474")

        #rich

        #save
        save = QPushButton()
        save.setIcon(QIcon("iconlar/save.png"))

        save.clicked.connect(self.save_clicked)
        save.setFixedSize(80, 20)
        #save

        #opentext
        opentext = QPushButton()
        opentext.setIcon(QIcon("iconlar/open.png"))
        opentext.clicked.connect(self.opentext_clicked)
        opentext.setFixedSize(80, 20)
        #opentext

        #fontSet
        self.fontCombo = QFontComboBox()

        self.fontCombo.activated.connect(self.fontSelect)
        self.fontCombo.setFixedSize(150, 20)
        #fontSet

        #fontSize
        self.spiner = QSpinBox()
        self.spiner.valueChanged.connect(self.sizeSelect)
        self.spiner.setFixedSize(130, 20)

        #fontSize

        #colorSelect
        self.colorButton = QPushButton()
        self.colorButton.setIcon(QIcon("iconlar/color.png"))
        self.colorButton.clicked.connect(self.colorButton_clicked)
        self.colorButton.setFixedSize(50, 20)

        #colorSelect

        #Addimage
        self.addImage = QPushButton()
        self.addImage.clicked.connect(self.addImage_clicked)
        self.addImage.setIcon(QIcon("iconlar/add.png"))
        self.addImage.setFixedSize(30, 20)
        #Addimage

        #FindWord
        self.findWord = QPushButton()
        self.findWord.setIcon(QIcon("iconlar/find.png"))
        self.findWord.clicked.connect(self.findWord_clicked)
        self.findWord.setFixedSize(30, 20)

        #FindWord

        #hizalamaveBoldİtalicMenuOpen
        self.widg1 = QWidget()
        self.widg2 = QWidget()

        self.toolBox = QToolBox()
        self.toolBox.setFixedSize(150, 300)

        self.ortala = QPushButton()
        self.ortala.setFixedSize(30, 40)
        self.ortala.setIcon(QIcon("iconlar/center"))
        self.ortala.clicked.connect(self.yaziyi_ortala)
        self.sağyasla = QPushButton()
        self.sağyasla.setIcon(QIcon("iconlar/right.png"))
        self.sağyasla.setFixedSize(30, 40)
        self.sağyasla.clicked.connect(self.yaziyi_sagayasla)
        self.solaYasla = QPushButton()
        self.solaYasla.setIcon(QIcon("iconlar/left.png"))
        self.solaYasla.setFixedSize(30, 40)
        self.solaYasla.clicked.connect(self.yaziyi_solayasla)
        self.ikiyanayasla = QPushButton()
        self.ikiyanayasla.setIcon(QIcon("iconlar/justify_align.png"))
        self.ikiyanayasla.setFixedSize(30, 40)
        self.ikiyanayasla.clicked.connect(self.yaziyi_ikiyanayasla)
        self.bold = QPushButton()
        self.bold.setFixedSize(30, 40)
        self.bold.setIcon(QIcon("iconlar/Bold.png"))
        self.bold.clicked.connect(self.bold_yap)
        self.italic = QPushButton()
        self.italic.setIcon(QIcon("iconlar/italic.png"))
        self.italic.setFixedSize(30, 40)
        self.italic.clicked.connect(self.italic_yap)
        self.altıçizili = QPushButton()
        self.altıçizili.setIcon(QIcon("iconlar/underline.png"))
        self.altıçizili.setFixedSize(30, 40)
        self.altıçizili.clicked.connect(self.altiniciz)

        self.layoutHizalama = QGridLayout()
        self.layoutHizalama.addWidget(self.ortala, 0, 0)
        self.layoutHizalama.addWidget(self.sağyasla, 1, 0)
        self.layoutHizalama.addWidget(self.solaYasla, 2, 0)
        self.layoutHizalama.addWidget(self.ikiyanayasla, 3, 0)

        self.layoutBoldİtalic = QGridLayout()
        self.layoutBoldİtalic.addWidget(self.bold, 0, 0)
        self.layoutBoldİtalic.addWidget(self.italic, 1, 0)
        self.layoutBoldİtalic.addWidget(self.altıçizili, 2, 0)

        self.widg1.setLayout(self.layoutHizalama)
        self.widg2.setLayout(self.layoutBoldİtalic)

        self.toolBox.addItem(self.widg1, "hizalamalar")
        self.toolBox.addItem(self.widg2, "Yazı biçimleri")
        #hizalamaBoldİtalicMenuOpen

        layout.addWidget(save, 5, 1)
        layout.addWidget(self.richText, 0, 0, -1, 1)
        layout.addWidget(opentext, 6, 1)
        layout.addWidget(self.spiner, 4, 1)
        layout.addWidget(self.fontCombo, 3, 1)
        layout.addWidget(self.colorButton, 7, 1)
        layout.addWidget(self.addImage, 8, 1)
        layout.addWidget(self.findWord, 9, 1)
        layout.addWidget(self.toolBox, 10, 1)

        self.setLayout(layout)

    def yaziyi_ortala(self):
        self.richText.setAlignment(Qt.AlignCenter)

    def yaziyi_sagayasla(self):
        self.richText.setAlignment(Qt.AlignRight)

    def yaziyi_solayasla(self):
        self.richText.setAlignment(Qt.AlignLeft)

    def yaziyi_ikiyanayasla(self):
        self.richText.setAlignment(Qt.AlignJustify)

    def bold_yap(self):
        if (self.say_bold % 2 == 0):

            self.richText.setFontWeight(QFont.Bold)
        else:

            self.richText.setFontWeight(QFont.Normal)

        self.say_bold = self.say_bold + 1

    def italic_yap(self):
        if (self.say_italic % 2 == 0):
            self.richText.setFontItalic(True)
        else:
            self.richText.setFontItalic(False)

        self.say_italic = self.say_italic + 1

    def altiniciz(self):

        if (self.say_altciz % 2 == 0):
            self.richText.setFontUnderline(True)
        else:
            self.richText.setFontUnderline(False)

        self.say_altciz = self.say_altciz + 1

    def richText_changed(self):
        text = self.richText.toPlainText()

        temp = 0

        for i in text.split(" "):

            temp = temp + 1

        self.setWindowTitle("kelime sayısı:" + str(temp))
        #burası henüz tam doğru çalışmıyor

    def findWord_clicked(self):

        aranan, onay = QInputDialog.getText(self, " aranan kelimeyi giriniz:",
                                            "kelime bul")

        if not aranan:
            return
        col = QColorDialog.getColor(self.richText.textColor(), self)
        if not col.isValid():
            return
        fmt = QTextCharFormat()
        fmt.setForeground(col)
        print("\nfmt.setForeground(col)", col)
        fmt.setFontPointSize(14)

        self.richText.moveCursor(QTextCursor.Start)

        self.countWords = 0
        # Find whole words
        while self.richText.find(aranan, QTextDocument.FindWholeWords):
            self.mergeFormatOnWordOrSelection(fmt)
            self.countWords += 1

        QMessageBox.information(
            self, "Information",
            "word->`{text}` {countWords}` adet bulundu".format(
                text=aranan, countWords=self.countWords))

    def mergeFormatOnWordOrSelection(self, format):
        cursor = self.richText.textCursor()
        if not cursor.hasSelection():
            cursor.select(QTextCursor.WordUnderCursor)
        cursor.mergeCharFormat(format)
        self.richText.mergeCurrentCharFormat(format)

    def addImage_clicked(self):
        imagePath = QFileDialog.getOpenFileName(self, 'Open file')
        document = self.richText.document()
        cursor = QTextCursor(document)
        cursor.insertImage(imagePath[0])
        #getopenfilename tupple döndürdüğü için ve 0.indexde path olduğu için 0.indexi verdik

    def colorButton_clicked(self):
        color = QColorDialog.getColor()
        self.richText.setTextColor(color)

    def sizeSelect(self):
        self.richText.setFontPointSize(self.spiner.value())

    def fontSelect(self):
        self.richText.setFont(self.fontCombo.currentFont())

    def opentext_clicked(self):

        try:

            filename = QFileDialog.getOpenFileName(self, 'Open File')

            if filename[0]:

                f = open(filename[0], 'r')

                with f:

                    data = f.read()
                    self.richText.setText(data)
        except:
            QMessageBox.about(
                self, "Onu nasıl açayım be güzel kardeşim",
                "Kötü şeyler oldu olur arada öyle şeyler takma eğer sorun devam ederse bildir"
            )

    def save_clicked(self):
        try:
            fname = QFileDialog.getExistingDirectory(self, 'Open f', '/home')

            metin, onay = QInputDialog.getText(self, " dosyanın adını giriniz",
                                               "dosya adı:")

            metinuzantı, onay = QInputDialog.getText(
                self, " dosyanın uzantısını giriniz", "dosya uzantısı:")
            metinad = ""
            uzantıad = ""
            if onay == True:

                metinad = metin
                uzantıad = metinuzantı

            with open(fname + "/" + metinad + "." + uzantıad, 'w') as f:
                my_text = self.richText.toPlainText()
                f.write(my_text)
            QMessageBox.about(self, "Bilgilendirme", "Başarı ile kaydedildi")
        except:
            QMessageBox.about(self, "Runtime ERROR", "Birşey oldu")
예제 #28
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()
예제 #29
0
class NodeManagerWidget(QWidget):
    signal_new_node = pyqtSignal(Node)

    def __init__(self,
                 parent: QWidget = None,
                 scene: 'PMGraphicsScene' = None):
        super().__init__(parent)
        self.groups = ['simple_calc', 'logic', 'matrix', 'plot', 'io']
        self.node_info_dic: Dict[str, List[Dict[str, object]]] = {
            key: []
            for key in self.groups
        }

        self.setLayout(QVBoxLayout())
        self.top_layout = QHBoxLayout()
        self.layout().addLayout(self.top_layout)
        self.button_edit = QPushButton('Edit')
        self.button_add = QPushButton('Add')
        self.top_layout.addWidget(self.button_edit)
        self.top_layout.addWidget(self.button_add)
        self.button_edit.clicked.connect(self.on_edit)
        self.button_add.clicked.connect(self.on_add)
        self.toolbox = QToolBox()
        self.list_widgets: Dict[str, QListWidget] = {}
        for text in self.groups:
            list_widget = QListWidget()
            list_widget.doubleClicked.connect(self.on_item_double_clicked)
            self.layout().addWidget(self.toolbox)
            self.toolbox.addItem(list_widget, text)
            self.list_widgets[text] = list_widget
        self.scene: 'PMGraphicsScene' = scene
        self.load_nodes()

    def on_add(self):
        group = self.get_current_list_widget_group()
        self.add_node_info({
            'text': 'untitled',
            'inputs': ['input1'],
            'outputs': ['output1'],
            'code': '',
            'params': [],
            'icon': '',
            'group': group,
            'ports_changeable': [False, False]
        })

    def on_edit(self):
        list_widget = self.toolbox.currentWidget()
        curr_row = list_widget.currentRow()

        if curr_row >= 0:
            dic = self.node_info_dic[self.toolbox.itemText(
                self.toolbox.currentIndex())][curr_row]
            edit_layout = QHBoxLayout()
            input_widget = QLineEdit()
            edit_layout.addWidget(input_widget)
            check_button = QPushButton(text='check')
            edit_layout.addWidget(check_button)
            input_widget.setText(repr(dic['params']))
            views = [('line_edit', 'text', 'Node Text', dic['text']),
                     ('bool', 'inputs_changeable', 'Input Ports Changeable',
                      dic['ports_changeable'][0]),
                     ('bool', 'outputs_changeable', 'Output Ports Changeble',
                      dic['ports_changeable'][1]),
                     ('text_edit', 'code', 'Input Python Code', dic['code'],
                      'python'),
                     ('entry_list', 'inputs', 'Set Inputs',
                      [[None] * len(dic['inputs']),
                       dic['inputs']], lambda: None),
                     ('entry_list', 'outputs', 'Set Outputs',
                      [[None] * len(dic['outputs']),
                       dic['outputs']], lambda: None),
                     ('file', 'icon', 'Set Icon', dic['icon']),
                     ('choose_box', 'group', 'Group Name', dic['group'],
                      self.groups)]
            sp = SettingsPanel(parent=None, views=views)
            dialog = QDialog(self)

            def verify():
                try:
                    text = input_widget.text()
                    l = eval(text)
                    if isinstance(l, list):
                        dialog2 = QDialog(dialog)
                        sp2 = SettingsPanel(parent=None, views=l)
                        dialog2.setLayout(QHBoxLayout())
                        dialog2.layout().addWidget(sp2)
                        dialog2.layout().addLayout(edit_layout)
                        dialog2.exec_()

                except:
                    import traceback
                    traceback.print_exc()

            check_button.clicked.connect(verify)
            dialog.setLayout(QVBoxLayout())
            dialog.layout().addWidget(sp)
            dialog.layout().addLayout(edit_layout)
            dialog.exec_()
            dic = sp.get_value()
            params = None
            try:
                params = eval(input_widget.text())
            except:
                import traceback
                traceback.print_exc()
            group = self.get_current_list_widget_group()
            if isinstance(params, list):
                self.node_info_dic[group][curr_row]['params'] = params
            self.node_info_dic[group][curr_row]['text'] = dic['text']
            self.node_info_dic[group][curr_row]['icon'] = dic['icon']
            self.node_info_dic[group][curr_row]['code'] = dic['code']
            self.node_info_dic[group][curr_row]['inputs'] = dic['inputs'][1]
            self.node_info_dic[group][curr_row]['outputs'] = dic['outputs'][1]
            self.node_info_dic[group][curr_row]['group'] = dic['group']
            self.node_info_dic[group][curr_row]['ports_changeable'] = [
                dic['inputs_changeable'], dic['outputs_changeable']
            ]
            list_widget.item(curr_row).setText(dic['text'])

            self.save_node_templetes()
            self.load_nodes()
        else:
            return

    def add_node(self,
                 text: str,
                 inputs: List[str],
                 outputs: List[str],
                 ports_changeable: List[bool],
                 params_str: str = '',
                 icon_path: str = '',
                 func_str: str = ''):
        """
        添加新的节点
        """
        node_id = self.scene.new_id()
        input_ports = [
            CustomPort(node_id + ':input:%d' % int(i + 1),
                       text=name,
                       port_type='input') for i, name in enumerate(inputs)
        ]
        output_ports = [
            CustomPort(node_id + ':output:%d' % int(i + 1),
                       text=name,
                       port_type='output') for i, name in enumerate(outputs)
        ]
        node = Node(canvas=self.scene,
                    node_id=node_id,
                    text=text,
                    input_ports=input_ports,
                    output_ports=output_ports,
                    icon_path=icon_path)
        content = FlowContentForFunction(node)
        content.set_function(func_str, 'function')
        content.set_params(params_str)
        content.ports_changable = ports_changeable
        node.set_content(content)
        self.scene.add_node(node)

    def on_item_double_clicked(self):
        list_widget: QListWidget = self.toolbox.currentWidget()
        group = self.get_current_list_widget_group()
        curr_row = list_widget.currentRow()
        if curr_row >= 0:
            node_info = self.node_info_dic[group][curr_row]
            text: str = node_info.get('text')
            inputs: List[str] = node_info.get('inputs')
            outputs: List[str] = node_info.get('outputs')
            code: str = node_info.get('code')
            params: str = node_info.get('params')
            icon_path: str = node_info.get('icon')
            ports_changeable: List[bool] = node_info.get('ports_changeable')

            self.add_node(text, inputs, outputs, ports_changeable, params,
                          icon_path, code)

    def add_node_info(self, info_dic: Dict[str, object]):
        """
        add new infomation of node
        """
        group = self.get_current_list_widget_group()
        text = info_dic.get('text')
        self.get_current_list_widget().addItem(text)
        print(group)
        self.node_info_dic[group].append(info_dic)
        pass

    def get_current_list_widget(self) -> QListWidget:
        return self.toolbox.currentWidget()

    def get_current_list_widget_group(self) -> str:
        return self.toolbox.itemText(self.toolbox.currentIndex())

    def load_nodes(self):
        """
        加载节点
        加载节点之后,可以
        """
        import pandas
        self.node_info_dic = {key: [] for key in self.groups}
        df = pandas.read_csv(
            os.path.join(os.path.dirname(__file__), 'lib', 'test.csv'))
        # for k in self.node_info_dic:
        for i in range(df.shape[0]):
            row = df.loc[i]
            dic = {
                'text': row['text'] if not pandas.isna(row['text']) else '',
                'code': row['code'] if not pandas.isna(row['code']) else '',
                'inputs': json.loads(row['inputs']),
                'outputs': json.loads(row['outputs']),
                'params': json.loads(row['params'])
            }
            dic['icon'] = row['icon'] if not pandas.isna(row['icon']) else ''
            dic['group'] = row['group'] if not pandas.isna(
                row.get('group')) else 'simple_calc'
            ports_changeable = row.get('ports_changeable')
            dic['ports_changeable'] = json.loads(
                ports_changeable) if ports_changeable is not None else [
                    False, False
                ]
            self.node_info_dic[dic['group']].append(dic)
        self.refresh_list()

    def save_node_templetes(self):
        import pandas

        columns = [
            'text', 'inputs', 'outputs', 'ports_changeable', 'params', 'icon',
            'group', 'code'
        ]
        content = []
        node_infos = []
        for k in self.node_info_dic:
            node_infos += self.node_info_dic[k]

        for node_info in node_infos:
            text = node_info.get('text')
            icon = node_info.get('icon')
            inputs = json.dumps(node_info.get('inputs'))
            outputs = json.dumps(node_info.get('outputs'))
            ports_changeable = json.dumps(node_info.get('ports_changeable'))
            params = json.dumps(node_info.get('params'))
            code = node_info.get('code')
            group = node_info.get('group')
            content.append([
                text, inputs, outputs, ports_changeable, params, icon, group,
                code
            ])
        df = pandas.DataFrame(content, columns=columns)

        df.to_csv(os.path.join(os.path.dirname(__file__), 'lib', 'test.csv'))

    def refresh_list(self):
        for k in self.node_info_dic:
            node_infos = self.node_info_dic[k]
            list_widget = self.list_widgets[k]
            list_widget.clear()
            for info in node_infos:
                list_widget.addItem(info['text'])
예제 #30
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(970, 650)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.splitter = QtWidgets.QSplitter(self.centralwidget)
        self.splitter.setOrientation(QtCore.Qt.Horizontal)
        self.splitter.setHandleWidth(1)
        self.splitter.setObjectName("splitter")
        self.horizontalLayout.addWidget(self.splitter)
        MainWindow.setCentralWidget(self.centralwidget)

        # 文件树形目录浏览器
        self.tree = QTreeView()
        self.model = QtWidgets.QFileSystemModel()
        self.model.setRootPath('')
        self.nameFile = ["*.png", "*.jpg", "*.jpeg"]
        self.model.setNameFilterDisables(False)
        self.model.setNameFilters(self.nameFile)
        self.tree.setModel(self.model)
        self.tree.setAnimated(False)
        self.tree.setIndentation(20)
        self.tree.setWindowTitle("Dir View")
        self.tree.setSortingEnabled(True)
        self.tree.setColumnHidden(1, True)
        self.tree.setColumnHidden(2, True)
        self.tree.setColumnHidden(3, True)
        self.tree.doubleClicked.connect(self.openFileFromTreeList)
        # 图库管理器
        self.tree_2 = QTreeWidget()
        self.tree_2.setColumnCount(1)
        # 设置表头信息:隐藏表头
        self.tree_2.setHeaderHidden(1)
        # 设置root和root2为self.tree的子树,所以root和root2就是跟节点
        root = QTreeWidgetItem(self.tree_2)
        root2 = QTreeWidgetItem(self.tree_2)
        # 设置根节点的名称
        root.setText(0, '第一节点')
        root2.setText(0, '第二节点')
        # 为root节点设置子结点
        child1 = QTreeWidgetItem(root)
        child1.setText(0, 'child1')
        child1.setText(1, 'name1')
        child2 = QTreeWidgetItem(root)
        # 设置child2节点的图片
        child2.setText(0, 'child2')
        child2.setText(1, 'name2')

        # 实例化QToolBox
        self.toolBox = QToolBox()
        # 设置左侧导航栏 toolBox 在左右拉拽时的最小宽度
        self.toolBox.setMinimumWidth(100)
        # 给QToolBox添加两个子项目
        self.toolBox.addItem(self.tree, "文件资源")
        self.toolBox.addItem(self.tree_2, "图库")

        # 给QSplitter添加第一个窗体(QToolBox)
        self.splitter.addWidget(self.toolBox)

        #菜单栏
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(10, 10, 820, 30))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.menu1_file = QtWidgets.QMenu(self.menubar)
        self.menu1_file.setObjectName("menu1_file")
        self.menu2_edit = QtWidgets.QMenu(self.menubar)
        self.menu2_edit.setObjectName("menu2_edit")
        self.menu3_imageLib = QtWidgets.QMenu(self.menubar)
        self.menu3_imageLib.setObjectName("menu3_imageLib")
        self.menu4_image = QtWidgets.QMenu(self.menubar)
        self.menu4_image.setObjectName("menu4_image")
        self.menu6_user = QtWidgets.QMenu(self.menubar)
        self.menu6_user.setObjectName("menu6_user")
        self.menu5_help = QtWidgets.QMenu(self.menubar)
        self.menu5_help.setObjectName("menu5_help")
        MainWindow.setMenuBar(self.menubar)

        #menu Action
        #################action1######################
        self.action_1_1 = QtWidgets.QAction(MainWindow)
        self.action_1_1.setObjectName("action_1_1")  #打开
        self.action_1_1.triggered.connect(self.openfile)
        self.action_1_2 = QtWidgets.QAction(MainWindow)
        self.action_1_2.setObjectName("action_1_2")  #保存
        self.action_1_3 = QtWidgets.QAction(MainWindow)
        self.action_1_3.setObjectName("action_1_3")  #退出
        #################action2######################
        self.action_2_1 = QtWidgets.QAction(MainWindow)
        self.action_2_1.setObjectName("action_2_1")  #图片编辑
        self.action_2_1.triggered.connect(self.openChildWindow)
        #################action3######################
        self.action_3_1 = QtWidgets.QAction(MainWindow)
        self.action_3_1.setObjectName("action_3_1")  #图库管理器
        self.action_3_1.triggered.connect(self.imageLibUi)
        #################action4######################
        self.action_4_1 = QtWidgets.QAction(MainWindow)
        self.action_4_1.setObjectName("action_4_1")  # 添加图片
        self.action_4_2 = QtWidgets.QAction(MainWindow)
        self.action_4_2.setObjectName("action_4_2")  # 删除图片
        self.action_4_3 = QtWidgets.QAction(MainWindow)
        self.action_4_3.setObjectName("action_4_3")  # 重命名
        #################action5######################
        self.action_5 = QtWidgets.QAction(MainWindow)
        self.action_5.setObjectName("action_5")  #帮助
        #################action6######################
        self.action_6 = QtWidgets.QAction(MainWindow)
        self.action_6.setObjectName("action_6")  #用户管理
        self.action_6.triggered.connect(self.userManager)

        #给menu添加Action
        self.menu1_file.addAction(self.action_1_1)  #打开
        self.menu1_file.addAction(self.action_1_2)  #保存
        self.menu1_file.addAction(self.action_1_3)  #退出
        self.menu2_edit.addAction(self.action_2_1)  #图片编辑
        self.menu3_imageLib.addAction(self.action_3_1)  #图库管理器
        self.menu4_image.addAction(self.action_4_1)  #添加图片
        self.menu4_image.addAction(self.action_4_2)  #删除图片
        self.menu4_image.addAction(self.action_4_3)  #重命名
        self.menu6_user.addAction(self.action_6)  #用户管理
        self.menu5_help.addAction(self.action_5)  #帮助
        self.menubar.addAction(self.menu1_file.menuAction())
        self.menubar.addAction(self.menu2_edit.menuAction())
        self.menubar.addAction(self.menu3_imageLib.menuAction())
        self.menubar.addAction(self.menu4_image.menuAction())
        self.menubar.addAction(self.menu5_help.menuAction())
        self.menubar.addAction(self.menu6_user.menuAction())

        #Icon
        icon = QtGui.QIcon()
        icon2 = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("Icon/openfile.png"), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        icon2.addPixmap(QtGui.QPixmap("Icon/edit.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.action_1_1.setIcon(icon)
        self.action_2_1.setIcon(icon2)

        #工具栏
        self.toolBar = QtWidgets.QToolBar(MainWindow)
        self.toolBar.setInputMethodHints(QtCore.Qt.ImhHiddenText
                                         | QtCore.Qt.ImhSensitiveData)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.toolBar.addAction(self.action_1_1)
        self.toolBar.addAction(self.action_2_1)

        #状态栏
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        #初始化默认窗体
        #初始化默认窗体(图片显示窗体)
        self.imageView = ImageView()
        # 在主窗口里添加子窗口
        self.splitter.addWidget(self.imageView)

        #是普通用户还是管理员
        self

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        # 创建默认存放文件的文件夹:
        cur_dir = "C:"
        folder_name = 'InfraredImage'
        if os.path.isdir("C:/InfraredImage"):
            print("Already exist!")
        else:
            os.mkdir(os.path.join(cur_dir, folder_name))
            os.mkdir("C:/InfraredImage/TmpImg")

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "红外图像质量客观评价系统V1.0"))

        #导航栏名字
        self.menu1_file.setTitle(_translate("MainWindow", "文件"))
        self.menu3_imageLib.setTitle(_translate("MainWindow", "图库管理"))
        self.menu4_image.setTitle(_translate("MainWindow", "图片管理"))
        self.menu2_edit.setTitle(_translate("MainWindow", "编辑"))
        self.menu6_user.setTitle(_translate("MainWindow", "用户管理"))
        self.menu5_help.setTitle(_translate("MainWindow", "帮助"))

        #action名字
        self.action_1_1.setText(_translate("MainWindow", "打开"))
        self.action_1_1.setShortcut(_translate("MainWindow", "Ctrl+O"))
        self.action_1_2.setText(_translate("MainWindow", "保存"))
        self.action_1_2.setShortcut(_translate("MainWindow", "Ctrl+S"))
        self.action_1_3.setText(_translate("MainWindow", "退出"))
        self.action_1_3.setShortcut(_translate("MainWindow", "Ctrl+E"))
        self.action_2_1.setText(_translate("MainWindow", "编辑图片"))
        self.action_3_1.setText(_translate("MainWindow", "图库管理器"))
        self.action_4_1.setText(_translate("MainWindow", "添加图片"))
        self.action_4_2.setText(_translate("MainWindow", "删除图片"))
        self.action_4_3.setText(_translate("MainWindow", "重命名"))
        self.action_5.setText(_translate("MainWindow", "Help ?"))
        self.action_6.setText(_translate("MainWindow", "用户管理器"))

        self.statusbar.showMessage("Ready")

    ##########################功能函数区###############################

    def openfile(self):
        # 设置文件扩展名过滤,注意用双分号间隔
        fileName1, filetype = QFileDialog.getOpenFileName(
            None, "选取文件", "C:/", "All Files (*);;Image (*.png *.jpg *.jpeg)")
        #显示图片,并初始化图片基本信息
        self.openImage(fileName1)

    # 从文件资源目录树打开图片
    def openFileFromTreeList(self, Qmodelidx):
        filePath = self.model.filePath(Qmodelidx)
        self.openImage(filePath)

        # 打开图片,并初始化图片基本信息
    def openImage(self, filePath):
        self.action_2_1.setEnabled(True)
        self.splitter.widget(1).setParent(None)
        self.splitter.insertWidget(1, self.imageView)
        img = QtGui.QPixmap(filePath).scaled(
            self.imageView.graphicsView.width(),
            self.imageView.graphicsView.height())
        self.imageView.graphicsView.setPixmap(img)
        self.newPic = Image.open(filePath)
        self.statusbar.showMessage("打开图片")
        self.imageView.listWidget.item(1).setText("大小: " +
                                                  str(self.newPic.size))
        self.imageView.listWidget.item(2).setText("色彩通道: " + self.newPic.mode)
        self.imageView.listWidget.item(3).setText("格式: " + self.newPic.format)
        self.imageView.listWidget.item(4).setText(
            "像素: " + str(self.newPic.getextrema()))
        self.imageView.listWidget.item(5).setText("文件: " + str(filePath))
        # # 要把新打开的图片,和所有修改过的图片,都存进tempPic.jpg里面,作为一个中间变量。
        self.newPic.save("C:/InfraredImage/TmpImg/tempPic.png")
        self.newPic = "C:/InfraredImage/TmpImg/tempPic.png"

    # 打开图片处理子窗口函
    def openChildWindow(self):
        childUi = childWindow()
        if childUi.exec_() == QtWidgets.QDialog.Accepted:
            pass

    #打开图库管理窗口
    def imageLibUi(self):
        self.imageLibUi = ImageLibUi()
        # 把QSplitter的指定位置的窗体从QSplitter中剥离
        self.splitter.widget(1).setParent(None)
        # 在QSplitter的指定位置载入新窗体
        self.splitter.insertWidget(1, self.imageLibUi)
        # 打开图库管理窗口时将图片编辑器设为不可用
        self.action_2_1.setEnabled(False)

    #用户管理
    def userManager(self):
        self.userWindow = UserManagerUi()
        # 把QSplitter的指定位置的窗体从QSplitter中剥离
        self.splitter.widget(1).setParent(None)
        # 在QSplitter的指定位置载入新窗体
        self.splitter.insertWidget(1, self.userWindow)
        # 打开图库管理窗口时将图片编辑器设为不可用
        self.action_2_1.setEnabled(False)
예제 #31
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.create_main_window_actions([
            QActionProperties(
                name=main_window_constants.EXPORT_ACTION_NAME,
                icon=QIcon(':/icons/export'),
                text='&Export',
                shortcut='Ctrl+E',
                status_tip='Export to Python code',
                triggered=self.export_diagram,
            ),
            QActionProperties(
                name=main_window_constants.DELETE_ACTON_NAME,
                icon=QIcon(':/icons/delete'),
                text='&Delete',
                shortcut='Delete',
                status_tip='Delete item from diagram',
                triggered=self.delete_item,
            ),
            QActionProperties(
                name=main_window_constants.TO_FRONT_ACTION_NAME,
                icon=QIcon(':/icons/bring_to_front'),
                text='Bring to &Front',
                shortcut='Ctrl+F',
                status_tip='Bring item to front',
                triggered=self.bring_to_front,
            ),
            QActionProperties(
                name=main_window_constants.TO_BACK_ACTION_NAME,
                icon=QIcon(':/icons/send_to_back'),
                text='Send to &Back',
                shortcut='Ctrl+B',
                status_tip='Send item to back',
                triggered=self.send_to_back,
            ),
        ])

        self.create_file_menu()
        self.create_edit_menu()
        self.create_frameworks_toolbar()
        self.create_edit_diagram_toolbar()
        self.create_pointer_toolbar()
        self.create_diagram_scene_and_view()
        self.create_framework_toolbox()

        self.layout = QHBoxLayout()
        self.layout.addWidget(self.framework_toolbox)
        self.layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(self.layout)

        self.setWindowTitle(main_window_constants.MAIN_WINDOW_TITLE)
        self.setCentralWidget(self.widget)

    # Create methods.
    def create_main_window_actions(
            self, main_window_actions: List[QActionProperties]):
        self.main_window_actions = dict()
        for main_window_action in main_window_actions:
            self.main_window_actions[main_window_action.name] = QAction(
                main_window_action.icon,
                main_window_action.text,
                self,
                shortcut=main_window_action.shortcut,
                statusTip=main_window_action.status_tip,
                triggered=main_window_action.triggered,
            )

    def create_file_menu(self):
        self.file_menu = self.menuBar().addMenu(
            main_window_constants.FILE_MENU_NAME)
        self.file_menu.addAction(
            self.main_window_actions[main_window_constants.EXPORT_ACTION_NAME])

    def create_edit_menu(self):
        self.edit_menu = self.menuBar().addMenu(
            main_window_constants.EDIT_MENU_NAME)
        self.edit_menu.addAction(
            self.main_window_actions[main_window_constants.DELETE_ACTON_NAME])
        self.edit_menu.addSeparator()
        self.edit_menu.addAction(self.main_window_actions[
            main_window_constants.TO_FRONT_ACTION_NAME])
        self.edit_menu.addAction(self.main_window_actions[
            main_window_constants.TO_BACK_ACTION_NAME])

    def create_frameworks_toolbar(self):
        self.frameworks_label = QLabel(main_window_constants.FRAMEWORKS_LABEL)

        self.frameworks_combobox = QComboBox()
        self.frameworks_combobox.setEditable(False)
        for framework in frameworks_utils.get_sorted_frameworks_list():
            self.frameworks_combobox.addItem(framework)

        self.frameworks_toolbar = self.addToolBar(
            main_window_constants.FRAMEWORKS_TOOLBAR_NAME)
        self.frameworks_toolbar.addWidget(self.frameworks_label)
        self.frameworks_toolbar.addWidget(self.frameworks_combobox)

    def create_edit_diagram_toolbar(self):
        self.edit_diagram_toolbar = self.addToolBar(
            main_window_constants.DIAGRAM_EDIT_TOOLBAR_NAME)
        self.edit_diagram_toolbar.addAction(
            self.main_window_actions[main_window_constants.DELETE_ACTON_NAME])
        self.edit_diagram_toolbar.addAction(self.main_window_actions[
            main_window_constants.TO_FRONT_ACTION_NAME])
        self.edit_diagram_toolbar.addAction(self.main_window_actions[
            main_window_constants.TO_BACK_ACTION_NAME])

    def create_pointer_toolbar(self):
        pointer_button = QToolButton()
        pointer_button.setCheckable(True)
        pointer_button.setChecked(True)
        pointer_button.setIcon(QIcon(':/icons/pointer'))

        line_pointer_button = QToolButton()
        line_pointer_button.setCheckable(True)
        line_pointer_button.setIcon(QIcon(':/icons/line_pointer'))

        self.pointer_type_group = QButtonGroup()
        self.pointer_type_group.addButton(pointer_button,
                                          DiagramScene.move_item)
        self.pointer_type_group.addButton(line_pointer_button,
                                          DiagramScene.insert_line)
        self.pointer_type_group.buttonClicked[int].connect(
            self.pointer_group_clicked)

        scene_scale_combo = QComboBox()
        scene_scale_combo.addItems(main_window_constants.DIAGRAM_SCENE_SCALES)
        scene_scale_combo.setCurrentIndex(
            main_window_constants.DIAGRAM_SCENE_SCALES.index(
                main_window_constants.DIAGRAM_SCENE_DEFAULT_SCALE))
        scene_scale_combo.currentIndexChanged[str].connect(
            self.scene_scale_changed)

        self.pointer_toolbar = self.addToolBar(
            main_window_constants.POINTER_TYPE_TOOLBAR_NAME)
        self.pointer_toolbar.addWidget(pointer_button)
        self.pointer_toolbar.addWidget(line_pointer_button)
        self.pointer_toolbar.addWidget(scene_scale_combo)

    def create_diagram_scene_and_view(self):
        self.scene = DiagramScene(self.edit_menu)
        self.scene.setSceneRect(
            QRectF(0, 0, main_window_constants.DIAGRAM_SCENE_SIZE,
                   main_window_constants.DIAGRAM_SCENE_SIZE))
        self.scene.item_inserted.connect(self.item_inserted)
        self.view = QGraphicsView(self.scene)

    def create_framework_toolbox(self):
        framework_layers = frameworks_utils.get_framework_layers(
            self.get_selected_framework())

        self.framework_layers_button_group = QButtonGroup()
        self.framework_layers_button_group.setExclusive(False)
        self.framework_layers_button_group.buttonClicked[int].connect(
            self.framework_layers_button_group_clicked)

        layout = QGridLayout()
        for framework_layer in framework_layers:
            layout.addWidget(
                self.create_framework_layer_widget(framework_layer()))

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        item_widget = QWidget()
        item_widget.setLayout(layout)

        self.framework_toolbox = QToolBox()
        self.framework_toolbox.setSizePolicy(
            QSizePolicy(
                QSizePolicy.Maximum,
                QSizePolicy.Ignored,
            ), )
        self.framework_toolbox.setMinimumWidth(item_widget.sizeHint().width())
        self.framework_toolbox.addItem(item_widget,
                                       main_window_constants.LAYERS)

    # Callback methods.
    def export_diagram(self):
        nodes = self.get_nodes_from_scene()

        if len(nodes) == 0:
            return

        edges = self.get_edges_from_scene()
        nodes_mapping = self.create_nodes_mapping(nodes)
        uni_graph = graph_utils.create_graph_from_qt_elements(
            nodes, edges, nodes_mapping)
        bi_graph = graph_utils.create_graph_from_qt_elements(
            nodes, edges, nodes_mapping, is_bi_directional=True)

        is_one_connected_component = graph_utils.is_one_connected_component(
            bi_graph)
        graph_topological_sort = graph_utils.create_graph_topological_sort(
            uni_graph)
        root_nodes = graph_utils.get_root_nodes(uni_graph)
        is_all_root_nodes_are_input_layers = graph_utils.is_all_root_nodes_are_input_layers(
            nodes, root_nodes)

        if not is_one_connected_component:
            self.show_model_graph_eval_error_msg(
                main_window_constants.MODEL_GRAPH_MULTIPLE_COMPONENTS_ERROR_MSG
            )
        elif graph_topological_sort is None:
            self.show_model_graph_eval_error_msg(
                main_window_constants.MODEL_GRAPH_CYCLE_ERROR_MSG)
        elif not is_all_root_nodes_are_input_layers:
            self.show_model_graph_eval_error_msg(
                main_window_constants.
                MODEL_GRAPH_ROOT_NODE_IS_NOT_INPUT_ERROR_MSG)
        else:
            input_definitions = self.build_input_definitions(
                map(nodes.__getitem__, root_nodes))
            layer_definitions = self.build_layer_definitions(
                nodes, graph_topological_sort, root_nodes)
            model_connections = self.build_model_connections(
                nodes, uni_graph, graph_topological_sort, root_nodes)
            framework_template = frameworks_utils.get_formatted_framework_template(
                self.get_selected_framework(),
                input_definitions,
                layer_definitions,
                model_connections,
            )

            file_path, _ = QFileDialog.getSaveFileName(
                self,
                'Export Model As',
                'talzeeq.py',
                'Python Language (*.py);;'
                'All files (*.*)',
            )

            if file_path:
                with open(file_path, 'w') as fp:
                    fp.write(framework_template)

    def delete_item(self):
        for item in self.scene.selectedItems():
            if isinstance(item, DiagramItem):
                item.remove_arrows()
            self.scene.removeItem(item)

    def bring_to_front(self):
        for selected_item in self.scene.selectedItems():
            z_value = 0
            for item in selected_item.collidingItems():
                if item.zValue() >= z_value and isinstance(item, DiagramItem):
                    z_value = item.zValue() + 0.1
            selected_item.setZValue(z_value)

    def send_to_back(self):
        for selected_item in self.scene.selectedItems():
            z_value = 0
            for item in selected_item.collidingItems():
                if item.zValue() <= z_value and isinstance(item, DiagramItem):
                    z_value = item.zValue() - 0.1
            selected_item.setZValue(z_value)

    def pointer_group_clicked(self, index: int):
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def scene_scale_changed(self, scale: str):
        new_scale = int(
            scale[:scale.index(main_window_constants.
                               DIAGRAM_SCENE_SCALE_PERCENT)]) / 100.0
        old_transform = self.view.transform()
        self.view.resetTransform()
        self.view.translate(old_transform.dx(), old_transform.dy())
        self.view.scale(new_scale, new_scale)

    def item_inserted(self, item: DiagramItem):
        self.pointer_type_group.button(DiagramScene.move_item).setChecked(True)
        self.scene.set_mode(self.pointer_type_group.checkedId())
        layer_index = frameworks_utils.get_framework_layer_index(
            self.get_selected_framework(),
            item.framework_layer.__class__,
        )
        self.framework_layers_button_group.button(layer_index).setChecked(
            False)

    def framework_layers_button_group_clicked(self, id: int):
        buttons = self.framework_layers_button_group.buttons()

        for button in buttons:
            if self.framework_layers_button_group.button(id) != button:
                button.setChecked(False)

        if self.framework_layers_button_group.button(id).isChecked():
            self.scene.set_item_type(id)
            self.scene.set_framework_name(self.get_selected_framework())
            self.scene.set_mode(DiagramScene.insert_item)
        else:
            self.scene.set_mode(DiagramScene.move_item)

    # Helper methods.
    def get_selected_framework(self) -> str:
        return str(self.frameworks_combobox.currentText())

    def get_nodes_from_scene(self) -> List[DiagramItem]:
        return list(
            filter(lambda item: isinstance(item, DiagramItem),
                   self.scene.items()))

    def get_edges_from_scene(self) -> List[Arrow]:
        return list(
            filter(lambda item: isinstance(item, Arrow), self.scene.items()))

    def create_nodes_mapping(
            self, nodes: List[DiagramItem]) -> Dict[DiagramItem, int]:
        return {node: index for index, node in enumerate(nodes)}

    def show_model_graph_eval_error_msg(self, message: str):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setText(main_window_constants.MODEL_GRAPH_EVAL_ERROR_MSG_TEXT)
        msg.setInformativeText(message)
        msg.setWindowTitle(
            main_window_constants.MODEL_GRAPH_EVAL_ERROR_MSG_TEXT)
        msg.exec_()

    def build_input_definitions(self, root_nodes: List[DiagramItem]) -> str:
        input_definitions = list()
        for node in root_nodes:
            input_definitions.append(
                node.get_framework_layer().layer_definition())
        return ', '.join(input_definitions)

    def build_layer_definitions(
        self,
        nodes: List[DiagramItem],
        graph_topological_sort: List[int],
        root_nodes: List[int],
    ) -> str:
        layer_definitions = list()
        for element in graph_topological_sort:
            if element not in root_nodes:
                layer_definitions.append(
                    nodes[element].get_framework_layer().layer_definition())
        return '\n'.join(layer_definitions)

    def build_model_connections(
        self,
        nodes: List[DiagramItem],
        graph: List[List[int]],
        graph_topological_sort: List[int],
        root_nodes: List[int],
    ) -> str:
        model_connections = list()

        for element in graph_topological_sort:
            parents = list()
            is_root = list()
            for node in range(len(graph)):
                if element in graph[node]:
                    parents.append(nodes[node].get_framework_layer())
                    is_root.append(node in root_nodes)

            layer_connections = nodes[element].get_framework_layer(
            ).layer_connections(parents, is_root)
            if layer_connections:
                model_connections.append(layer_connections)

        return '\n'.join(model_connections)

    def create_framework_layer_widget(
            self, framework_layer: LayerInterface) -> QWidget:
        button = QToolButton()
        button.setText(framework_layer.layer_name())
        button.setCheckable(True)
        self.framework_layers_button_group.addButton(
            button,
            frameworks_utils.get_framework_layer_index(
                self.get_selected_framework(),
                framework_layer.__class__,
            ),
        )

        layout = QVBoxLayout()
        layout.addWidget(button)

        widget = QWidget()
        widget.setLayout(layout)

        return widget
예제 #32
0
class MainWindow(QMainWindow):
    InsertTextButton = 10

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

        self.createActions()
        self.createMenus()
        self.createToolBox()

        self.scene = DiagramScene(self.itemMenu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))
        self.scene.itemInserted.connect(self.itemInserted)
        self.scene.textInserted.connect(self.textInserted)
        self.scene.itemSelected.connect(self.itemSelected)

        self.createToolbars()

        layout = QHBoxLayout()
        layout.addWidget(self.toolBox)
        self.view = QGraphicsView(self.scene)
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("Diagramscene")

    def backgroundButtonGroupClicked(self, button):
        buttons = self.backgroundButtonGroup.buttons()
        for myButton in buttons:
            if myButton != button:
                button.setChecked(False)

        text = button.text()
        if text == "Blue Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background1.png')))
        elif text == "White Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background2.png')))
        elif text == "Gray Grid":
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background3.png')))
        else:
            self.scene.setBackgroundBrush(QBrush(QPixmap(':/images/background4.png')))

        self.scene.update()
        self.view.update()

    def buttonGroupClicked(self, id):
        buttons = self.buttonGroup.buttons()
        for button in buttons:
            if self.buttonGroup.button(id) != button:
                button.setChecked(False)

        if id == self.InsertTextButton:
            self.scene.setMode(DiagramScene.InsertText)
        else:
            self.scene.setItemType(id)
            self.scene.setMode(DiagramScene.InsertItem)

    def deleteItem(self):
        for item in self.scene.selectedItems():
            if isinstance(item, DiagramItem):
                item.removeArrows()
            self.scene.removeItem(item)

    def pointerGroupClicked(self, i):
        self.scene.setMode(self.pointerTypeGroup.checkedId())

    def bringToFront(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() >= zValue and isinstance(item, DiagramItem)):
                zValue = item.zValue() + 0.1
        selectedItem.setZValue(zValue)

    def sendToBack(self):
        if not self.scene.selectedItems():
            return

        selectedItem = self.scene.selectedItems()[0]
        overlapItems = selectedItem.collidingItems()

        zValue = 0
        for item in overlapItems:
            if (item.zValue() <= zValue and isinstance(item, DiagramItem)):
                zValue = item.zValue() - 0.1
        selectedItem.setZValue(zValue)

    def itemInserted(self, item):
        self.pointerTypeGroup.button(DiagramScene.MoveItem).setChecked(True)
        self.scene.setMode(self.pointerTypeGroup.checkedId())
        self.buttonGroup.button(item.diagramType).setChecked(False)

    def textInserted(self, item):
        self.buttonGroup.button(self.InsertTextButton).setChecked(False)#
        self.scene.setMode(self.pointerTypeGroup.checkedId())

    def currentFontChanged(self, font):
        self.handleFontChange()

    def fontSizeChanged(self, font):
        self.handleFontChange()

    def sceneScaleChanged(self, scale):
        newScale = float(scale[:scale.index("%")]) / 100.0
        oldMatrix = self.view.transform()
        self.view.resetTransform()
        self.view.translate(oldMatrix.dx(), oldMatrix.dy())
        self.view.scale(newScale, newScale)

    def textColorChanged(self):
        self.textAction = self.sender()
        self.fontColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/textpointer.png',
                        QColor(self.textAction.data())))
        self.textButtonTriggered()

    def itemColorChanged(self):
        self.fillAction = self.sender()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon( ':/images/floodfill.png',
                        QColor(self.fillAction.data())))
        self.fillButtonTriggered()

    def lineColorChanged(self):
        self.lineAction = self.sender()
        self.lineColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/linecolor.png',
                        QColor(self.lineAction.data())))
        self.lineButtonTriggered()

    def textButtonTriggered(self):
        self.scene.setTextColor(QColor(self.textAction.data()))

    def fillButtonTriggered(self):
        self.scene.setItemColor(QColor(self.fillAction.data()))

    def lineButtonTriggered(self):
        self.scene.setLineColor(QColor(self.lineAction.data()))

    def handleFontChange(self):
        font = self.fontCombo.currentFont()
        font.setPointSize(int(self.fontSizeCombo.currentText()))
        if self.boldAction.isChecked():
            font.setWeight(QFont.Bold)
        else:
            font.setWeight(QFont.Normal)
        font.setItalic(self.italicAction.isChecked())
        font.setUnderline(self.underlineAction.isChecked())

        self.scene.setFont(font)

    def itemSelected(self, item):
        font = item.font()
        color = item.defaultTextColor()
        self.fontCombo.setCurrentFont(font)
        self.fontSizeCombo.setEditText(str(font.pointSize()))
        self.boldAction.setChecked(font.weight() == QFont.Bold)
        self.italicAction.setChecked(font.italic())
        self.underlineAction.setChecked(font.underline())

    def about(self):
        QMessageBox.about(self, "About Diagram Scene",
                "The <b>Diagram Scene</b> example shows use of the graphics framework.")

    def createToolBox(self):
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.setExclusive(False)
        self.buttonGroup.buttonClicked[int].connect(self.buttonGroupClicked)

        layout = QGridLayout()
        layout.addWidget(self.createCellWidget("Conditional", DiagramItem.Conditional),
                0, 0)
        layout.addWidget(self.createCellWidget("Process", DiagramItem.Step), 0,
                1)
        layout.addWidget(self.createCellWidget("Input/Output", DiagramItem.Io),
                1, 0)

        textButton = QToolButton()
        textButton.setCheckable(True)
        self.buttonGroup.addButton(textButton, self.InsertTextButton)
        textButton.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30)))
        textButton.setIconSize(QSize(50, 50))

        textLayout = QGridLayout()
        textLayout.addWidget(textButton, 0, 0, Qt.AlignHCenter)
        textLayout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter)
        textWidget = QWidget()
        textWidget.setLayout(textLayout)
        layout.addWidget(textWidget, 1, 1)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        itemWidget = QWidget()
        itemWidget.setLayout(layout)

        self.backgroundButtonGroup = QButtonGroup()
        self.backgroundButtonGroup.buttonClicked.connect(self.backgroundButtonGroupClicked)

        backgroundLayout = QGridLayout()
        backgroundLayout.addWidget(self.createBackgroundCellWidget("Blue Grid",
                ':/images/background1.png'), 0, 0)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("White Grid",
                ':/images/background2.png'), 0, 1)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("Gray Grid",
                ':/images/background3.png'), 1, 0)
        backgroundLayout.addWidget(self.createBackgroundCellWidget("No Grid",
                ':/images/background4.png'), 1, 1)

        backgroundLayout.setRowStretch(2, 10)
        backgroundLayout.setColumnStretch(2, 10)

        backgroundWidget = QWidget()
        backgroundWidget.setLayout(backgroundLayout)

        self.toolBox = QToolBox()
        self.toolBox.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.toolBox.setMinimumWidth(itemWidget.sizeHint().width())
        self.toolBox.addItem(itemWidget, "Basic Flowchart Shapes")
        self.toolBox.addItem(backgroundWidget, "Backgrounds")

    def createActions(self):
        self.toFrontAction = QAction(
                QIcon(':/images/bringtofront.png'), "Bring to &Front",
                self, shortcut="Ctrl+F", statusTip="Bring item to front",
                triggered=self.bringToFront)

        self.sendBackAction = QAction(
                QIcon(':/images/sendtoback.png'), "Send to &Back", self,
                shortcut="Ctrl+B", statusTip="Send item to back",
                triggered=self.sendToBack)

        self.deleteAction = QAction(QIcon(':/images/delete.png'),
                "&Delete", self, shortcut="Delete",
                statusTip="Delete item from diagram",
                triggered=self.deleteItem)

        self.exitAction = QAction("E&xit", self, shortcut="Ctrl+X",
                statusTip="Quit Scenediagram example", triggered=self.close)

        self.boldAction = QAction(QIcon(':/images/bold.png'),
                "Bold", self, checkable=True, shortcut="Ctrl+B",
                triggered=self.handleFontChange)

        self.italicAction = QAction(QIcon(':/images/italic.png'),
                "Italic", self, checkable=True, shortcut="Ctrl+I",
                triggered=self.handleFontChange)

        self.underlineAction = QAction(
                QIcon(':/images/underline.png'), "Underline", self,
                checkable=True, shortcut="Ctrl+U",
                triggered=self.handleFontChange)

        self.aboutAction = QAction("A&bout", self, shortcut="Ctrl+B",
                triggered=self.about)

    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.exitAction)

        self.itemMenu = self.menuBar().addMenu("&Item")
        self.itemMenu.addAction(self.deleteAction)
        self.itemMenu.addSeparator()
        self.itemMenu.addAction(self.toFrontAction)
        self.itemMenu.addAction(self.sendBackAction)

        self.aboutMenu = self.menuBar().addMenu("&Help")
        self.aboutMenu.addAction(self.aboutAction)

    def createToolbars(self):
        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.deleteAction)
        self.editToolBar.addAction(self.toFrontAction)
        self.editToolBar.addAction(self.sendBackAction)

        self.fontCombo = QFontComboBox()
        self.fontCombo.currentFontChanged.connect(self.currentFontChanged)

        self.fontSizeCombo = QComboBox()
        self.fontSizeCombo.setEditable(True)
        for i in range(8, 30, 2):
            self.fontSizeCombo.addItem(str(i))
        validator = QIntValidator(2, 64, self)
        self.fontSizeCombo.setValidator(validator)
        self.fontSizeCombo.currentIndexChanged.connect(self.fontSizeChanged)

        self.fontColorToolButton = QToolButton()
        self.fontColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fontColorToolButton.setMenu(
                self.createColorMenu(self.textColorChanged, Qt.black))
        self.textAction = self.fontColorToolButton.menu().defaultAction()
        self.fontColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/textpointer.png',
                        Qt.black))
        self.fontColorToolButton.setAutoFillBackground(True)
        self.fontColorToolButton.clicked.connect(self.textButtonTriggered)

        self.fillColorToolButton = QToolButton()
        self.fillColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.fillColorToolButton.setMenu(
                self.createColorMenu(self.itemColorChanged, Qt.white))
        self.fillAction = self.fillColorToolButton.menu().defaultAction()
        self.fillColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/floodfill.png',
                        Qt.white))
        self.fillColorToolButton.clicked.connect(self.fillButtonTriggered)

        self.lineColorToolButton = QToolButton()
        self.lineColorToolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.lineColorToolButton.setMenu(
                self.createColorMenu(self.lineColorChanged, Qt.black))
        self.lineAction = self.lineColorToolButton.menu().defaultAction()
        self.lineColorToolButton.setIcon(
                self.createColorToolButtonIcon(':/images/linecolor.png',
                        Qt.black))
        self.lineColorToolButton.clicked.connect(self.lineButtonTriggered)

        self.textToolBar = self.addToolBar("Font")
        self.textToolBar.addWidget(self.fontCombo)
        self.textToolBar.addWidget(self.fontSizeCombo)
        self.textToolBar.addAction(self.boldAction)
        self.textToolBar.addAction(self.italicAction)
        self.textToolBar.addAction(self.underlineAction)

        self.colorToolBar = self.addToolBar("Color")
        self.colorToolBar.addWidget(self.fontColorToolButton)
        self.colorToolBar.addWidget(self.fillColorToolButton)
        self.colorToolBar.addWidget(self.lineColorToolButton)

        pointerButton = QToolButton()
        pointerButton.setCheckable(True)
        pointerButton.setChecked(True)
        pointerButton.setIcon(QIcon(':/images/pointer.png'))
        linePointerButton = QToolButton()
        linePointerButton.setCheckable(True)
        linePointerButton.setIcon(QIcon(':/images/linepointer.png'))

        self.pointerTypeGroup = QButtonGroup()
        self.pointerTypeGroup.addButton(pointerButton, DiagramScene.MoveItem)
        self.pointerTypeGroup.addButton(linePointerButton,
                DiagramScene.InsertLine)
        self.pointerTypeGroup.buttonClicked[int].connect(self.pointerGroupClicked)

        self.sceneScaleCombo = QComboBox()
        self.sceneScaleCombo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.sceneScaleCombo.setCurrentIndex(2)
        self.sceneScaleCombo.currentIndexChanged[str].connect(self.sceneScaleChanged)

        self.pointerToolbar = self.addToolBar("Pointer type")
        self.pointerToolbar.addWidget(pointerButton)
        self.pointerToolbar.addWidget(linePointerButton)
        self.pointerToolbar.addWidget(self.sceneScaleCombo)

    def createBackgroundCellWidget(self, text, image):
        button = QToolButton()
        button.setText(text)
        button.setIcon(QIcon(image))
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.backgroundButtonGroup.addButton(button)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createCellWidget(self, text, diagramType):
        item = DiagramItem(diagramType, self.itemMenu)
        icon = QIcon(item.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.buttonGroup.addButton(button, diagramType)

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    def createColorMenu(self, slot, defaultColor):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        colorMenu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.createColorIcon(color), name, self,
                    triggered=slot)
            action.setData(QColor(color)) 
            colorMenu.addAction(action)
            if color == defaultColor:
                colorMenu.setDefaultAction(action)
        return colorMenu

    def createColorToolButtonIcon(self, imageFile, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(imageFile)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    def createColorIcon(self, color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)
예제 #33
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)
예제 #34
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()
예제 #35
0
class QueryUI(QWidget):
    def __init__(self):
        super().__init__()
        try:
            self.keyValues = getOfficialKeys()
        except RequestException:
            logging.warning(
                "There was a problem with the internet connection. You will not be able to see the existing keys."
            )
        self.onClearPolygonF = lambda: None
        self.onPolygonEnabledF = lambda: None
        self.onPolygonDisabledF = lambda: None
        self.currentHtml = EMPTY_HTML
        self.initUI()

    def initUI(self):
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.requestAreaWidget = QToolBox()
        self.requestAreaWidget.layout().setSpacing(1)

        self.requestTabs = QTabWidget()
        self.requestTabs.setUsesScrollButtons(True)
        self.requestTabs.currentChanged.connect(self.__updateTabSizes__)
        self.requestAreaWidget.addItem(self.requestTabs, "Requests")

        self.requestOps = RequestsOperations(self)
        self.requestAreaWidget.addItem(self.requestOps, "Operations")

        self.generalConfig = GlobalOverpassSettingUI(self)
        self.requestAreaWidget.addItem(self.generalConfig, "General")

        self.disambiguationWidget = DisambiguationWidget(
            self.__getRequestByName__, self.__applyTableRow__, self)
        self.requestAreaWidget.addItem(self.disambiguationWidget,
                                       "Disambiguation")

        self.headers = self.requestAreaWidget.findChildren(
            QAbstractButton, "qt_toolbox_toolboxbutton")
        self.requestAreaWidget.currentChanged.connect(
            self.__onToolTabChanged__)
        self.headers[0].setIcon(QIcon(os.path.join(picturesDir,
                                                   "arrowUp.png")))
        for i in range(1, len(self.headers)):
            self.headers[i].setIcon(
                QIcon(os.path.join(picturesDir, "arrowDown.png")))

        self.layout.addWidget(self.requestAreaWidget)

        self.setLayout(self.layout)

    def __getRequestByName__(self, requestName):
        for requestWidget in self.findChildren(RequestWidget):
            if requestWidget.getName() == requestName:
                return requestWidget.getRequest()
        return None

    def __applyTableRow__(self, name, data):
        filters, ids = data
        for requestWidget in self.findChildren(RequestWidget):
            if requestWidget.getName() == name:
                for newFilter in filters:
                    requestWidget.addFilter(newFilter)
                break

        if len(ids) > 0:
            idsRequestName = SetNameManagement.getUniqueSetName()
            request = OverpassRequest(OsmType.WAYS, Surround.NONE,
                                      idsRequestName)
            request.setIds(ids)
            self.addRequest(request)

            differenceOpName = SetNameManagement.getUniqueSetName()
            self.requestOps.addOp(OverpassDiff(name, differenceOpName),
                                  [idsRequestName])
            self.requestOps.setOutputSet(differenceOpName)

        logging.info("Configuration from the table row has been applied.")

    def __onToolTabChanged__(self, i):
        for h in range(len(self.headers)):
            if h == i:
                self.headers[h].setIcon(
                    QIcon(os.path.join(picturesDir, "arrowUp.png")))
            else:
                self.headers[h].setIcon(
                    QIcon(os.path.join(picturesDir, "arrowDown.png")))

    def __updateTabSizes__(self, index):
        for i in range(self.requestTabs.count()):
            if i != index:
                self.requestTabs.widget(i).setSizePolicy(
                    QSizePolicy.Ignored, QSizePolicy.Ignored)

        if index >= 0:
            self.requestTabs.widget(index).setSizePolicy(
                QSizePolicy.Preferred, QSizePolicy.Preferred)
            self.requestTabs.widget(index).resize(
                self.requestTabs.widget(index).minimumSizeHint())
            self.requestTabs.widget(index).adjustSize()

    def setOnRequestChanged(self, f):
        self.requestTabs.currentChanged.connect(f)

    def addRequestByFilters(self, filters=None):
        requestWidget = RequestWidget(self, self.keyValues)
        setName = requestWidget.requestName
        requestWidget.changePage(self.currentHtml)
        self.requestTabs.addTab(requestWidget, setName)
        self.requestOps.addRequest(setName)
        self.disambiguationWidget.addSet(setName)

        if filters is not None:
            for filter in filters:
                requestWidget.addFilter(filter)

    def addRequest(self, request):
        if not SetNameManagement.isAvailable(request.name):
            raise ValueError("There is another request with the same name.")
        else:
            SetNameManagement.assign(request.name)

        requestWidget = RequestWidget(self, self.keyValues, request)
        requestWidget.changePage(self.currentHtml)
        self.requestTabs.addTab(requestWidget, request.name)
        self.requestOps.addRequest(request.name)
        self.disambiguationWidget.addSet(request.name)

    def removeRequest(self):
        requestName = self.requestTabs.currentWidget().getName()
        self.requestOps.removeSetAndDependencies(requestName)
        self.disambiguationWidget.removeSet(requestName)
        currentRequestWidget = self.requestTabs.currentWidget()
        SetNameManagement.releaseName(currentRequestWidget.requestName)
        self.requestTabs.removeTab(self.requestTabs.currentIndex())
        currentRequestWidget.deleteLater()

    def requestsCount(self):
        return self.requestTabs.count()

    def getQuery(self):
        query = OverpassQuery(self.requestOps.outputSet())
        query.addDate(self.generalConfig.getDate())

        for i in range(self.requestTabs.count()):
            query.addRequest(self.requestTabs.widget(i).getRequest())

        for op in self.requestOps.ops:
            query.addSetsOp(op)

        return query

    def setQuery(self, query):
        self.reset()
        for request in query.requests:
            self.addRequest(request)
        for op in query.ops:
            self.requestOps.addOp(op)
        if query.config.get("date") is not None:
            self.generalConfig.setDate(
                datetime.strptime(query.config["date"], "%Y-%m-%dT00:00:00Z"))
        else:
            self.generalConfig.setDate()
        self.requestOps.setOutputSet(query.outputSet)

    def reset(self):
        while self.requestTabs.count() > 0:
            self.removeRequest()
        self.generalConfig.setDate()

    def updateMaps(self, html):
        self.currentHtml = html
        for requestWidget in self.findChildren(RequestWidget):
            requestWidget.changePage(html)

        return self.getCurrentMap()

    def updateMapFromRow(self):
        return self.updateMaps(
            self.disambiguationWidget.getHtmlFromSelectedRow())

    def getCurrentMap(self):
        if self.requestTabs.currentWidget() is None:
            return None
        else:
            return self.requestTabs.currentWidget().getMap()
예제 #36
0
class MainWindow(QMainWindow):
    InsertTextButton = 10
    items = {-2: "source", -3: "channel", -4: "sink"}

    def __init__(self):
        import _diagramscene_rc

        super(MainWindow, self).__init__()

        self.config_manipulations = FlumeConfig(self)
        properties_generator.dump_props()

        self.create_actions()
        self.create_menus()
        self.create_tool_box()
        self.clicked_button_id = 0

        self.scene = DiagramScene(self.item_menu)
        self.scene.setSceneRect(QRectF(0, 0, 5000, 5000))

        self.scene.itemInserted.connect(self.item_inserted)
        self.scene.textInserted.connect(self.text_inserted)
        self.scene.itemSelected.connect(self.item_selected)

        self.create_tool_bars()
        # self.scene.enable_grid()

        layout = QHBoxLayout()
        layout.addWidget(self.tool_box)
        self.view = QGraphicsView(self.scene)
        self.view.centerOn(0, 0)
        layout.addWidget(self.view)

        self.widget = QWidget()
        self.widget.setLayout(layout)

        self.setCentralWidget(self.widget)
        self.setWindowTitle("The Flume Illustrator")

    # noinspection PyAttributeOutsideInit,PyArgumentList
    def create_actions(self):

        self.to_front_action = QAction(QIcon(':/images/bringtofront.png'),
                                       "Bring to &Front", self, shortcut="Ctrl+F",
                                       statusTip="Bring item to front", triggered=self.bring_to_front)
        self.send_back_action = QAction(QIcon(':/images/sendtoback.png'),
                                        "Send to &Back", self, shortcut="Ctrl+B",
                                        statusTip="Send item to back", triggered=self.send_to_back)
        self.bold_action = QAction(QIcon(':/images/bold.png'),
                                   "Bold", self, checkable=True, shortcut="Ctrl+B",
                                   triggered=self.handle_font_change)
        self.italic_action = QAction(QIcon(':/images/italic.png'),
                                     "Italic", self, checkable=True, shortcut="Ctrl+I",
                                     triggered=self.handle_font_change)
        self.underline_action = QAction(QIcon(':/images/underline.png'),
                                        "Underline", self, checkable=True, shortcut="Ctrl+U",
                                        triggered=self.handle_font_change)

        self.delete_action = QAction(QIcon(':/images/delete.png'),
                                     "Delete", self, shortcut="Delete", statusTip='Delete item from diagram',
                                     triggered=self.delete_item)
        self.exit_action = QAction("Exit", self, shortcut="Ctrl+X",
                                   statusTip="Quit program", triggered=self.close)
        self.about_action = QAction("About", self, shortcut="Ctrl+B",
                                    triggered=self.about)
        self.load_config_action = QAction("Load", self, shortcut="Ctrl+O",
                                          statusTip="Load config file", triggered=self.config_manipulations.load_config)

        self.enable_grid_action = QAction("Enable grid", self, checkable=True, triggered=self.enable_grid)

    # noinspection PyAttributeOutsideInit
    def create_menus(self):
        self.file_menu = self.menuBar().addMenu("File")
        self.file_menu.addAction(self.load_config_action)
        self.file_menu.addAction(self.exit_action)

        self.item_menu = self.menuBar().addMenu("Item")
        self.item_menu.addAction(self.delete_action)
        self.item_menu.addSeparator()
        self.item_menu.addAction(self.to_front_action)
        self.item_menu.addAction(self.send_back_action)

        self.about_menu = self.menuBar().addMenu("Help")
        self.about_menu.addAction(self.about_action)

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_box(self):
        self.button_group = QButtonGroup()
        self.button_group.setExclusive(False)
        self.button_group.buttonClicked[int].connect(self.button_group_clicked)

        layout = QGridLayout()
        layout.addWidget(self.create_cell_widget("Source", "source"), 0, 0)
        layout.addWidget(self.create_cell_widget("Channel", "channel"), 0, 1)
        layout.addWidget(self.create_cell_widget("Sink", "sink"), 1, 0)

        text_button = QToolButton()
        text_button.setCheckable(True)
        self.button_group.addButton(text_button, self.InsertTextButton)
        text_button.setIcon(QIcon(QPixmap(':/images/textpointer.png').scaled(30, 30)))
        text_button.setIconSize(QSize(50, 50))

        text_layout = QGridLayout()
        text_layout.addWidget(text_button, 0, 0, Qt.AlignHCenter)
        text_layout.addWidget(QLabel("Text"), 1, 0, Qt.AlignCenter)
        text_widget = QWidget()
        text_widget.setLayout(text_layout)
        layout.addWidget(text_widget, 1, 1)

        layout.setRowStretch(3, 10)
        layout.setColumnStretch(2, 10)

        item_widget = QWidget()
        item_widget.setLayout(layout)

        self.tool_box = QToolBox()
        self.tool_box.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Ignored))
        self.tool_box.setMinimumWidth(item_widget.sizeHint().width())
        self.tool_box.addItem(item_widget, "Basic Flume Items")

    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
    def create_tool_bars(self):

        self.edit_tool_bar = self.addToolBar("Edit")
        self.edit_tool_bar.addAction(self.delete_action)
        self.edit_tool_bar.addAction(self.to_front_action)
        self.edit_tool_bar.addAction(self.send_back_action)

        self.edit_tool_bar.addAction(self.enable_grid_action)

        self.font_combo = QFontComboBox()
        self.font_combo.currentFontChanged.connect(self.current_font_changed)

        self.font_size_combo = QComboBox()
        self.font_size_combo.setEditable(True)
        for i in range(8, 30, 2):
            self.font_size_combo.addItem(str(i))
        validator = QIntValidator(2, 64, self)
        self.font_size_combo.setValidator(validator)
        self.font_size_combo.currentIndexChanged.connect(self.font_size_changed)

        self.font_color_tool_button = QToolButton()
        self.font_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.font_color_tool_button.setMenu(
            self.create_color_menu(self.text_color_changed, Qt.black))
        self.text_action = self.font_color_tool_button.menu().defaultAction()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               Qt.black))
        self.font_color_tool_button.setAutoFillBackground(True)
        self.font_color_tool_button.clicked.connect(self.text_button_triggered)

        self.fill_color_tool_button = QToolButton()
        self.fill_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.fill_color_tool_button.setMenu(
            self.create_color_menu(self.item_color_changed, Qt.white))
        self.fillAction = self.fill_color_tool_button.menu().defaultAction()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               Qt.white))
        self.fill_color_tool_button.clicked.connect(self.fill_button_triggered)

        self.line_color_tool_button = QToolButton()
        self.line_color_tool_button.setPopupMode(QToolButton.MenuButtonPopup)
        self.line_color_tool_button.setMenu(
            self.create_color_menu(self.line_color_changed, Qt.black))
        self.lineAction = self.line_color_tool_button.menu().defaultAction()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               Qt.black))
        self.line_color_tool_button.clicked.connect(self.line_button_triggered)

        self.text_tool_bar = self.addToolBar("Font")
        self.text_tool_bar.addWidget(self.font_combo)
        self.text_tool_bar.addWidget(self.font_size_combo)
        self.text_tool_bar.addAction(self.bold_action)
        self.text_tool_bar.addAction(self.italic_action)
        self.text_tool_bar.addAction(self.underline_action)

        self.color_tool_bar = self.addToolBar("Color")
        self.color_tool_bar.addWidget(self.font_color_tool_button)
        self.color_tool_bar.addWidget(self.fill_color_tool_button)
        self.color_tool_bar.addWidget(self.line_color_tool_button)

        self.loading_tool_bar = self.addToolBar("Load")
        self.loading_tool_bar.addAction(self.load_config_action)

        pointer_button = QToolButton()
        pointer_button.setCheckable(True)
        pointer_button.setChecked(True)
        pointer_button.setIcon(QIcon(":/images/pointer.png"))
        line_pointer_button = QToolButton()
        line_pointer_button.setCheckable(True)
        line_pointer_button.setIcon(QIcon(":/images/linepointer.png"))

        self.pointer_type_group = QButtonGroup()
        self.pointer_type_group.addButton(pointer_button, DiagramScene.MoveItem)
        self.pointer_type_group.addButton(line_pointer_button, DiagramScene.InsertLine)
        self.pointer_type_group.buttonClicked[int].connect(self.pointer_group_clicked)

        self.scene_scale_combo = QComboBox()
        self.scene_scale_combo.addItems(["50%", "75%", "100%", "125%", "150%"])
        self.scene_scale_combo.setCurrentIndex(2)
        self.scene_scale_combo.currentIndexChanged[str].connect(self.scene_scale_changed)

        self.pointer_tool_bar = self.addToolBar("Pointer type")
        self.pointer_tool_bar.addWidget(pointer_button)
        self.pointer_tool_bar.addWidget(line_pointer_button)
        self.pointer_tool_bar.addWidget(self.scene_scale_combo)

    def button_group_clicked(self, button_id):
        buttons = self.button_group.buttons()
        self.clicked_button_id = button_id
        for button in buttons:
            if self.button_group.button(button_id) != button:
                button.setChecked(False)
        if button_id == self.InsertTextButton:
            self.scene.set_mode(DiagramScene.InsertText)
        else:
            self.scene.set_item_type(self.items[button_id])
            self.scene.set_mode(DiagramScene.InsertItem)

    def delete_item(self):
        for item in self.scene.selectedItems():
            if isinstance(item, FlumeDiagramItem):
                item.remove_arrows()
            self.scene.removeItem(item)

    # noinspection PyTypeChecker,PyCallByClass
    def about(self):

        # noinspection PyArgumentList
        QMessageBox.about(self, "About Flume Illustrator", "The Flume illustrator shows config-file details")

    def pointer_group_clicked(self):
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def bring_to_front(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() >= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() + 0.1
        selected_item.setZValue(z_value)

    def send_to_back(self):
        if not self.scene.selectedItems():
            return

        selected_item = self.scene.selectedItems()[0]
        overlap_items = selected_item.collidingItems()

        z_value = 0
        for item in overlap_items:
            if item.zValue() <= z_value and isinstance(item, FlumeDiagramItem):
                z_value = item.zValue() - 0.1
        selected_item.setZValue(z_value)

    def scene_scale_changed(self, scale):
        new_scale = float(scale[:scale.index("%")]) / 100
        old_transform = self.view.transform()
        self.view.resetTransform()
        self.view.translate(old_transform.dx(), old_transform.dy())
        self.view.scale(new_scale, new_scale)

    def item_inserted(self, diagram_type):
        self.pointer_type_group.button(DiagramScene.MoveItem).setChecked(True)
        self.scene.set_mode(self.scene.DefaultMode)
        self.button_group.button(self.clicked_button_id).setChecked(False)

    def text_inserted(self, item):
        self.button_group.button(self.InsertTextButton).setChecked(False)
        self.scene.set_mode(self.pointer_type_group.checkedId())

    def current_font_changed(self, font):
        self.handle_font_change()

    def font_size_changed(self, font=None):
        self.handle_font_change()

    def text_color_changed(self):
        self.text_action = self.sender()
        self.font_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/textpointer.png',
                                               QColor(self.text_action.data())))
        self.text_button_triggered()

    def item_color_changed(self):
        self.fillAction = self.sender()
        self.fill_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/floodfill.png',
                                               QColor(self.fillAction.data())))
        self.fill_button_triggered()

    def line_color_changed(self):
        self.lineAction = self.sender()
        self.line_color_tool_button.setIcon(
            self.create_color_tool_button_icon(':/images/linecolor.png',
                                               QColor(self.lineAction.data())))
        self.line_button_triggered()

    def text_button_triggered(self):
        self.scene.set_text_color(QColor(self.text_action.data()))

    def fill_button_triggered(self):
        self.scene.set_item_color(QColor(self.fillAction.data()))

    def line_button_triggered(self):
        self.scene.set_line_color(QColor(self.lineAction.data()))

    def handle_font_change(self):
        font = self.font_combo.currentFont()
        font.setPointSize(int(self.font_size_combo.currentText()))
        if self.bold_action.isChecked():
            font.setWeight(QFont.Bold)
        else:
            font.setWeight(QFont.Normal)
        font.setItalic(self.italic_action.isChecked())
        font.setUnderline(self.underline_action.isChecked())

        self.scene.setFont(font)

    def item_selected(self, item):
        font = item.font()
        self.font_combo.setCurrentFont(font)
        self.font_size_combo.setEditText(str(font.pointSize()))
        self.bold_action.setChecked(font.weight() == QFont.Bold)
        self.italic_action.setChecked(font.italic())
        self.underline_action.setChecked(font.underline())

    def create_cell_widget(self, text, diagram_type):
        item = FlumeObject(diagram_type, "")
        icon = QIcon(item.pictogram.image())

        button = QToolButton()
        button.setIcon(icon)
        button.setIconSize(QSize(50, 50))
        button.setCheckable(True)
        self.button_group.addButton(button)  # , diagram_type

        layout = QGridLayout()
        layout.addWidget(button, 0, 0, Qt.AlignHCenter)
        layout.addWidget(QLabel(text), 1, 0, Qt.AlignHCenter)

        widget = QWidget()
        widget.setLayout(layout)

        return widget

    # noinspection PyArgumentList
    def create_color_menu(self, slot, default_color):
        colors = [Qt.black, Qt.white, Qt.red, Qt.blue, Qt.yellow]
        names = ["black", "white", "red", "blue", "yellow"]

        color_menu = QMenu(self)
        for color, name in zip(colors, names):
            action = QAction(self.create_color_icon(color), name, self,
                             triggered=slot)
            action.setData(QColor(color))
            color_menu.addAction(action)
            if color == default_color:
                color_menu.setDefaultAction(action)
        return color_menu

    @staticmethod
    def create_color_tool_button_icon(image_file, color):
        pixmap = QPixmap(50, 80)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        image = QPixmap(image_file)
        target = QRect(0, 0, 50, 60)
        source = QRect(0, 0, 42, 42)
        painter.fillRect(QRect(0, 60, 50, 80), color)
        painter.drawPixmap(target, image, source)
        painter.end()

        return QIcon(pixmap)

    @staticmethod
    def create_color_icon(color):
        pixmap = QPixmap(20, 20)
        painter = QPainter(pixmap)
        painter.setPen(Qt.NoPen)
        painter.fillRect(QRect(0, 0, 20, 20), color)
        painter.end()

        return QIcon(pixmap)

    def enable_grid(self):
        if self.enable_grid_action.isChecked():
            color = Qt.black
        else:
            color = Qt.white
        for i in range(50):
            for j in range(50):
                self.scene.addEllipse(i * 100, j * 100, 2, 2, QPen(color))