def main():
    """ Main loop to run text widget as applation
    """
    app = QApplication(sys.argv)

    mwTextEditor = QMainWindow()
    textEditorBar = EditorBar(mwTextEditor)
    textEditor = TextWidget(textEditorBar)

    textEditorBar.saveDocAsSignal.connect(textEditor.saveAs)
    textEditorBar.spellSignal.connect(textEditor.toggleSpell)
    textEditorBar.whiteSpaceSignal.connect(textEditor.togglewhiteSpace)
    textEditorBar.boldSignal.connect(textEditor.toggleBold)
    textEditorBar.italicSignal.connect(textEditor.toggleItalic)
    textEditorBar.underlineSignal.connect(textEditor.toggleUnderline)
    textEditorBar.strikethroughSignal.connect(textEditor.toggleStrikethrough)
    textEditorBar.subscriptSignal.connect(textEditor.toggleSubscript)
    textEditorBar.superscriptSignal.connect(textEditor.toggleSuperscript)

    textEditor.fontFormatSignal.connect(textEditorBar.toggleFormat)

    mwTextEditor.addToolBar(textEditorBar)
    mwTextEditor.setCentralWidget(textEditor)

    mwTextEditor.show()

    return app.exec_()
Exemple #2
0
    def build_ui(self, window: QMainWindow):
        container = QWidget()
        box = QVBoxLayout()

        self.tab_list = QTabWidget()
        self.gfx = dict()
        self.scene = dict()
        self.gfx[Scan.SIDE_LEFT] = self.__create_tab(Scan.SIDE_LEFT, "left")
        self.gfx[Scan.SIDE_TOP] = self.__create_tab(Scan.SIDE_TOP, "top")
        self.gfx[Scan.SIDE_RIGHT] = self.__create_tab(Scan.SIDE_RIGHT, "right")

        for side in Scan.SIDES:
            self.scene[side] = Scene()
            self.scene[side].addRect(0, 0, 2054, 2054)
            self.gfx[side].setScene(self.scene[side])

        box.addWidget(self.tab_list)

        container.setLayout(box)
        window.setCentralWidget(container)

        menu_bar = QMenuBar()
        file_menu: QMenu = menu_bar.addMenu("File")

        self.a_load: QAction = file_menu.addAction("Load Scans")
        file_menu.addSeparator()
        self.a_load_roi: QAction = file_menu.addAction("Load ROI")
        self.a_save_roi: QAction = file_menu.addAction("Save ROI")
        file_menu.addSeparator()
        a_exit: QAction = file_menu.addAction("Exit")
        a_exit.triggered.connect(window.close)

        edit_menu: QMenu = menu_bar.addMenu("Edit")
        self.a_add: QAction = edit_menu.addAction("Add point")

        window.setMenuBar(menu_bar)

        file_bar = QToolBar()
        self.slide_file = QSlider(orientation=Qt.Horizontal)
        self.slide_file.setRange(0, NUM_FILES - 1)
        self.slide_file.setSingleStep(1)
        self.slide_file.setPageStep(1)
        file_bar.addWidget(self.slide_file)

        self.slide_line = QSlider(orientation=Qt.Horizontal)
        self.slide_line.setRange(0, NUM_SCANS - 1)
        self.slide_line.setSingleStep(1)
        self.slide_line.setPageStep(16)
        file_bar.addWidget(self.slide_line)

        window.addToolBar(file_bar)
        window.setStatusBar(QStatusBar())

        window.setWindowTitle("Ruler")
        window.resize(1200, 700)
Exemple #3
0
def test_main():
    """Test main: see if drag and drop is working"""
    app = QApplication(sys.argv)
    mainwin = QMainWindow()
    mainwin.setWindowTitle('MTooButton')
    toolbar = QToolBar()
    mainwin.addToolBar(toolbar)
    button = MToolButton()
    button.setText('test')
    toolbar.addWidget(button)
    browser = MyWidget(mainwin)
    print((browser.acceptDrops()))
    mainwin.setCentralWidget(browser)
    mainwin.show()
    sys.exit(app.exec_())
Exemple #4
0
    def set_toolbar(self, main_window: QtWidgets.QMainWindow) -> None:
        """ツールバー作成"""

        self.toolbar = QtWidgets.QToolBar()
        self.toolbar.setWindowTitle('ToolBar')

        self.toolbar.addWidget(self.intpola_num_widget)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.method_widget)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.coord_widget)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.reset_bar_widget)
        self.toolbar.addSeparator()

        main_window.addToolBar(self.toolbar)
Exemple #5
0
    def init_ui(self):
        global cal
        cal = QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(self.tasks_show)

        tools = QMainWindow()
        exit_action = QAction(QIcon('pictures\exit.png'), 'Exit', tools)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(qApp.quit)
        add_action = QAction(QIcon('pictures\plus.png'), 'Add notification', tools)
        add_action.triggered.connect(self.add)
        list_action = QAction(QIcon("pictures\list.png"), "Notifications list", tools)
        list_action.triggered.connect(self.all_notifications)
        clear_action = QAction(QIcon("pictures\_basket.bmp"), "Clear all tasks", tools)
        clear_action.triggered.connect(self.clear_all)

        tools.toolbar = tools.addToolBar('Exit')
        tools.toolbar.addAction(add_action)
        tools.toolbar.addAction(list_action)
        tools.toolbar.addAction(clear_action)
        tools.toolbar.addAction(exit_action)

        vbox = QVBoxLayout()
        vbox.addWidget(tools)
        vbox.addWidget(cal)
        vbox.addStretch(1)


        self.setLayout(vbox)
        self.setGeometry(500, 400, 600, 600)
        self.setWindowTitle('Task reminder by Saf & CHu Calculated')
        self.setWindowIcon(QIcon('pictures\cal'))
        self.show()
        self.tasks_show()
Exemple #6
0
class CustomScene(MayaviScene):
    def _create_control(self, parent):
        # Create a panel as a wrapper of the scene toolkit control.  This
        # allows us to also add additional controls.
        self._panel = QMainWindow()

        # Add our toolbar to the panel.
        tbm = self._get_tool_bar_manager()
        self._tool_bar = tbm.create_tool_bar(self._panel)
        self._tool_bar.setMovable(False)
        self._panel.addToolBar(Qt.RightToolBarArea, self._tool_bar)

        # Create the actual scene content
        self._content = super(DecoratedScene,
                              self)._create_control(self._panel)
        self._panel.setCentralWidget(self._content)

        return self._panel
Exemple #7
0
def main():
    from PyQt5.QtWidgets import QApplication, QMainWindow
    app = QApplication(sys.argv)
    window = QMainWindow()
    widget = SettingsDialog.SettingsWidget({
        'LeakyIaF': ['Vm'],
        'Compartment': ['Vm', 'Im'],
        'HHChannel': ['Ik', 'Gk'],
        'ZombiePool': ['n', 'conc'],
        'ZombieBufPool': ['n', 'conc'],
        'HHChannel2D': ['Ik', 'Gk'],
        'CaConc': ['Ca']
    })
    d = QDialog()
    l = QHBoxLayout()
    d.setLayout(l)
    l.addWidget(widget)
    bar = sidebar()
    bar.addAction(mode_action(bar))
    bar.addAction(connector_action(bar))
    bar.addAction(settings_action(bar, d.show))
    window.addToolBar(bar)
    window.show()
    sys.exit(app.exec_())
    def setMenu(self):
        ''' Sets the menu, toolbar, user interface

        :return: None
        '''
        #setup actions
        quit_action = QAction('Quit', self)
        load_action = QAction('Load inputs', self)
        validate_action = QAction('Validate', self)
        submit_action = QAction('Submit', self)
        #setup triggered action
        load_action.triggered.connect(self.open_sheet)
        validate_action.triggered.connect(self.validate_sheet)
        submit_action.triggered.connect(self.submit_sheet)
        quit_action.triggered.connect(self.quit_app)
        #setup Toolbar
        toolbar = QMainWindow.addToolBar(self, 'Toolbar')
        toolbar.addAction(load_action)
        toolbar.addAction(validate_action)
        toolbar.addAction(submit_action)
        toolbar.addAction(quit_action)
Exemple #9
0
class PyGUIno:
    def __init__(self):
        # Set up all the window related stuff
        self._app = QApplication(sys.argv)
        self._window = QMainWindow()
        size = self._app.primaryScreen().size()
        self._window.resize(int(size.width()*0.7),
                            int(size.height()*0.8))
        self._window.setObjectName("PyGUIno")
        self._window.setWindowTitle('PyGUIno')
        self._window.setWindowIcon(QIcon('resources\\assets\\etsi.png'))
        self._centralwidget = QWidget(self._window)
        self._window.setCentralWidget(self._centralwidget)
        self._centralwidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.layout = QHBoxLayout()
        self._centralwidget.setLayout(self.layout)

        # Create the toolbar and the actions
        self.toolbar = QToolBar()
        save_action = QAction(QIcon('resources\\assets\\ic_save_3x.png'), 'Guardar', self._window)
        save_action.setStatusTip('Guarda la configuración de las gráficas actuales')
        load_action = QAction(QIcon('resources\\assets\\ic_open_in_new_18pt_3x.png'), 'Cargar', self._window)
        load_action.setStatusTip('Cargar la configuración de gráficas')
        self.connect_menu = QAction(QIcon('resources\\assets\\ic_settings_black_48dp.png'), 'Conectar', self._window)
        self.connect_menu.setStatusTip('Configuración de la conexión a Arduino')
        self.start_action = QAction(QIcon('resources\\assets\\ic_play_arrow_3x.png'), 'Comenzar', self._window)
        self.start_action.setEnabled(False)
        self.start_action.setStatusTip('Comienza la conexión con Arduino')
        self.stop_action = QAction(QIcon('resources\\assets\\ic_stop_3x.png'), 'Detener', self._window)
        self.stop_action.setEnabled(False)
        self.stop_action.setStatusTip('Detiene la conexión con Arduino')

        add_plot = QAction(QIcon('resources\\assets\\ic_timeline_48pt_3x.png'), 'Añadir gráfica', self._window)
        add_plot.setStatusTip('Añadir gráfica')

        board_selector = QComboBox()
        self.board_choices = []
        self.current_board = None
        schemas = os.listdir("resources\\schemas")

        self.widgetCoord = WidgetCoordinator()
        for schema in schemas:
            fd = open("resources\\schemas\\" + schema, 'r')
            data = json.load(fd)
            board_selector.addItem(data['name'])
            tmp = list()

            # añadir al dict los pines digitales
            for x in range(0, data['digital']):
                tmp.append(x)

            # añadir al dict los pines analogicos
            for x in range(data['digital'], data['digital'] + data['analog']):
                tmp.append("A"+str(x-data['digital']))

            self.board_choices.append((tmp, data["data_size"]))
            self.widgetCoord.data_size = data["data_size"]
            self.widgetCoord.pin_list = tmp
            self.current_board = tmp
            fd.close()

        # Signal handlers
        save_action.triggered.connect(self.save)
        load_action.triggered.connect(self.load)
        add_plot.triggered.connect(self.ini_graph_dialog)
        self.connect_menu.triggered.connect(self.comm_config)
        self.start_action.triggered.connect(self.start)
        self.stop_action.triggered.connect(self.stop)
        board_selector.currentIndexChanged.connect(self.switch_board)

        self.toolbar.addAction(save_action)
        self.toolbar.addAction(load_action)
        self.toolbar.addAction(add_plot)
        self.toolbar.addAction(self.connect_menu)
        self.toolbar.addAction(self.start_action)
        self.toolbar.addAction(self.stop_action)
        self.toolbar.addWidget(board_selector)

        self._window.addToolBar(self.toolbar)

        # Create status bar
        self.statusbar = QStatusBar(self._window)
        self._window.setStatusBar(self.statusbar)

        # Create Workspace area
        left_layout = QVBoxLayout()
        right_layout = QVBoxLayout()
        left_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setContentsMargins(0, 0, 0, 0)

        top_left_side = self.widgetCoord.plot_container
        top_right_side = self.widgetCoord.user_vars_table
        low_left_side = self.widgetCoord.debug_vars_widget
        low_right_side = self.widgetCoord.log_container

        # Prepare horizontal splitter and left and right vertical splitters
        horizontal_splitter = QSplitter(Qt.Horizontal)
        horizontal_splitter.setStyleSheet('background-color:rgb(239, 239, 239)')
        left_vertical_splitter = QSplitter(Qt.Vertical)
        left_vertical_splitter.setStyleSheet('background-color:rgb(239, 239, 239)')
        right_vertical_splitter = QSplitter(Qt.Vertical)
        right_vertical_splitter.setStyleSheet('background-color:rgb(239, 239, 239)')

        # First add left then add right
        left_vertical_splitter.addWidget(top_left_side)
        left_vertical_splitter.addWidget(low_left_side)
        left_layout.addWidget(left_vertical_splitter)

        # The same but on the right side
        right_vertical_splitter.addWidget(top_right_side)
        right_vertical_splitter.addWidget(low_right_side)
        right_layout.addWidget(right_vertical_splitter)

        # Finally add the vertical splitters to the horizontal splitter
        # And add it to the horizontal layout
        horizontal_splitter.addWidget(left_vertical_splitter)
        horizontal_splitter.addWidget(right_vertical_splitter)
        self.layout.addWidget(horizontal_splitter)
        self.layout.setContentsMargins(0, 0, 0, 0)

    def start_pygu(self):
        self._window.show()
        sys.exit(self._app.exec_())

    # Functions to trigger several menu actions
    def save(self):
        try:
            some_tuple = QFileDialog.getSaveFileName(parent=None, caption='Guardar',
                                                     directory='')
            abs_path = some_tuple[0]
            file = open(abs_path, 'w')
            data_to_save = json.dumps(self.widgetCoord.save(), sort_keys=True,
                                      indent=4, separators=(',', ': '))
            print(data_to_save)
            file.write(data_to_save)
            file.close()
        except Exception as e:
            print(e)

    def load(self):
        try:
            some_tuple = QFileDialog().getOpenFileName(parent=None, caption='Cargar',
                                                       directory='')
            abs_path = some_tuple[0]
            file = open(abs_path, 'r')
            content = json.load(file)
            self.widgetCoord.load(content)
            file.close()
        except Exception as e:
            print(e)

    def comm_config(self):
        Forms.ConnectionForm(self.connect_menu, self.start_action, self.stop_action,
                             self.widgetCoord)

    def stop(self):
        self.widgetCoord.stop_comm()
        self.connect_menu.setEnabled(True)
        self.start_action.setEnabled(False)
        self.stop_action.setEnabled(False)

    def start(self):
        self.widgetCoord.start_comm()
        self.start_action.setEnabled(False)
        self.stop_action.setEnabled(True)

    def ini_graph_dialog(self):
        Forms.PlotForm(self.widgetCoord, self.current_board,
                       self.widgetCoord.resource_dict)

    def switch_board(self, index):
        self.current_board = self.board_choices[index][0]
        self.widgetCoord.pin_list = self.board_choices[index][0]
        self.widgetCoord.data_size = self.board_choices[index][1]
Exemple #10
0
class TabDialog(QDialog):  ##########主界面
    def __init__(self, parent=None):
        super(TabDialog, self).__init__(parent)
        self.mustupdate = False
        self.setWindowOpacity(0.9)  #设置透明
        self.creatico()  #创建图标
        self.creatui()
        self.creattab()
        self.checkvision()  #运行检查升级函数QMainWindow

    def creatico(self):
        self.icon_title = QIcon()
        self.icon_title.addPixmap(QPixmap(":/img/title.ico"), QIcon.Normal,
                                  QIcon.Off)  #标题图表
        self.icon_save = QIcon()
        self.icon_save.addPixmap(QPixmap(":/img/save.ico"), QIcon.Normal,
                                 QIcon.Off)  #保存图表
        self.icon_help = QIcon()
        self.icon_help.addPixmap(QPixmap(":/img/help.ico"), QIcon.Normal,
                                 QIcon.Off)  # 帮助图表
        self.icon_aboat = QIcon()
        self.icon_aboat.addPixmap(QPixmap(":/img/about.ico"), QIcon.Normal,
                                  QIcon.Off)  #关于图表
        self.icon_github = QIcon()
        self.icon_github.addPixmap(QPixmap(":/img/github.ico"), QIcon.Normal,
                                   QIcon.Off)  #github图表

    def creatui(self):
        self.setWindowTitle('自定义报表程序')
        self.setGeometry(300, 300, 650, 270)
        #self.setFixedSize(self.width(), self.height())
        self.permissionsGroup = QGroupBox("服务器信息")
        self.permissionsLayout = QGridLayout()
        self.setWindowIcon(self.icon_title)
        ###############工具栏##########################
        self.qm = QMainWindow()
        exitAct = QAction(self.icon_save, "保存配置\nCtrl+S", self.qm)
        exitAct.setShortcut("Ctrl+S")
        exitAct.triggered.connect(self.saveconfig)
        self.toolbar = self.qm.addToolBar("save")
        exitAct1 = QAction(self.icon_help, "帮助\nCtrl+H", self.qm)
        exitAct1.setShortcut("Ctrl+H")
        exitAct1.triggered.connect(self.openhelp)
        exitAct2 = QAction(self.icon_aboat, "关于\nCtrl+I", self.qm)
        exitAct2.setShortcut("Ctrl+I")
        exitAct2.triggered.connect(self.openaboat)
        exitAct3 = QAction(self.icon_github, "查看源码\nCtrl+M", self.qm)
        exitAct3.setShortcut("Ctrl+M")
        exitAct3.triggered.connect(self.openaurl)
        self.toolbar.addAction(exitAct)
        self.toolbar.addAction(exitAct1)
        self.toolbar.addAction(exitAct2)
        self.toolbar.addAction(exitAct3)
        self.updatlabel = QLabel('', self.toolbar)
        self.updatlabel.setOpenExternalLinks(True)
        self.updatlabel.setFixedWidth(150)
        self.toolbar.addWidget(self.updatlabel)
        self.toolbar.setMovable(False)
        #self.toolbar.setFloatable(False)
        ###############服务器信息###############
        self.permissionsLayout.addWidget(QLabel('数据库', self.permissionsGroup),
                                         1, 0)
        self.le_host = QLineEdit('', self.permissionsGroup)
        self.le_host.editingFinished.connect(self.initserver)
        self.le_host.setInputMask('000.000.000.000')
        self.le_host.insert(config['server']['host'])
        self.le_host.setFixedWidth(100)
        self.le_host.setToolTip('这里要填数据库的IP')
        #print((self.le_host.height(),self.le_host.width()))
        self.permissionsLayout.addWidget(QLabel('端口', self.permissionsGroup),
                                         1, 2)
        self.le_port = QLineEdit('', self.permissionsGroup)
        self.le_port.setInputMask('99999')
        self.le_port.insert(config['server']['port'])
        self.le_port.editingFinished.connect(self.initserver)
        self.le_port.setFixedWidth(40)
        self.le_port.setToolTip('这里要填数据库的端口\n中联默认1443\n共济默认3307\n栅格默认3306')
        self.permissionsLayout.addWidget(QLabel('用户名', self.permissionsGroup),
                                         1, 4)
        self.le_usr = QLineEdit('', self.permissionsGroup)
        self.le_usr.insert(config['server']['user'])
        self.le_usr.editingFinished.connect(self.initserver)
        self.le_usr.setFixedWidth(40)
        self.le_usr.setToolTip('这里要填数据库的用户名\n中联默认sa\n共济默认gj\n栅格默认mysql')
        self.permissionsLayout.addWidget(QLabel('密码', self.permissionsGroup),
                                         1, 6)
        self.le_passwd = QLineEdit('', self.permissionsGroup)
        self.le_passwd.insert(config['server']['passwd'])
        self.le_passwd.editingFinished.connect(self.initserver)
        self.le_passwd.setFixedWidth(100)
        self.le_passwd.setToolTip(
            '这里要填数据库的密码\n中联无默认值\n共济默认xbrother\n栅格默认mysql')
        self.le_passwd.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.permissionsLayout.addWidget(QLabel('数据库名', self.permissionsGroup),
                                         1, 8)
        self.le_db = QLineEdit('', self.permissionsGroup)
        self.le_db.insert(config['server']['db'])
        self.le_db.setFixedWidth(80)
        self.le_db.setToolTip(
            '这里要填数据库名\n中联无默认值\n共济默认historyver1\n栅格默认sgdatabase')
        self.le_db.editingFinished.connect(self.initserver)
        ##################################
        self.permissionsLayout.addWidget(self.le_host, 1, 1)
        self.permissionsLayout.addWidget(self.le_port, 1, 3)
        self.permissionsLayout.addWidget(self.le_usr, 1, 5)
        self.permissionsLayout.addWidget(self.le_passwd, 1, 7)
        self.permissionsLayout.addWidget(self.le_db, 1, 9)
        self.permissionsGroup.setLayout(self.permissionsLayout)
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.qm)
        self.mainLayout.addWidget(self.permissionsGroup)
        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)

    def creattab(self):
        self.tabWidget = QTabWidget()
        self.ts1 = ri(config)
        self.ts2 = zhou()
        self.ts3 = yue(config)
        self.tabWidget.addTab(self.ts1, "日报")
        self.mainLayout.addWidget(self.tabWidget)
        self.tabWidget.addTab(self.ts2, "周报")
        self.mainLayout.addWidget(self.tabWidget)
        self.tabWidget.addTab(self.ts3, "月报")
        self.mainLayout.addWidget(self.tabWidget)

    ###################检测版本########################################
    def compare(self, a, b):  #比较版本号函数
        la = a.split('.')
        lb = b.split('.')
        f = 0
        if len(la) > len(lb):
            f = len(la)
        else:
            f = len(lb)
        for i in range(f):
            try:
                if int(la[i]) > int(lb[i]):
                    return '>'
                elif int(la[i]) == int(lb[i]):
                    continue
                else:
                    if i == 0:
                        self.mustupdate = True
                    else:
                        return '<'
            except IndexError as e:
                if len(la) > len(lb):
                    return '>'
                else:
                    return '<'
        return '='

    def checkvision(self):  # 在线获取版本号
        try:
            url = 'http://wechat.52hengshan.com/weixin/api/v1.0/appvison'
            s = requests.get(url=url, timeout=2).json()
        except:
            self.updatlabel.setText(
                "<html><head/><body><p><span style=\" text-decoration: underline; color:#00ff00;\">无法联网查找最新版本</span></a></p></body></html>"
            )
        else:
            blc_vi = self.compare(blc.vison, s['vison'])
            if blc_vi == '=':
                self.updatlabel.setText(
                    "<html><head/><body><p><span style=\" text-decoration: underline; color:#0000ff;\">已经是最新版本</span></a></p></body></html>"
                )
            elif blc_vi == '>' and not self.mustupdate:
                self.updatlabel.setText(
                    "<html><head/><body><p><span style=\" text-decoration: underline; color:#0000ff;\">你这个是内部版本吧<br>居然比发布版本要高</span></a></p></body></html>"
                )
            elif blc_vi == '<' and not self.mustupdate:
                self.updatlabel.setText(
                    "<html><head/><body><p><a href=\"{}\"><span style=\" text-decoration: underline; color:#ff0000;\">有最新版本,点此升级</span></a></p></body></html>"
                    .format(s['url']))
            elif blc_vi == '<' and self.mustupdate:
                self.tabWidget.setEnabled(False)
                self.updatlabel.setText(
                    "<html><head/><body><p><a href=\"{}\"><span style=\" text-decoration: underline; color:#ff0000;\">此版本有重大风险<br>不建议使用,必须升级</span></a></p></body></html>"
                    .format(s['url']))

    def initserver(self):  ##########从主界面获取的数据存入全局变量
        blc.host = self.le_host.text()
        blc.port = int(self.le_port.text())
        blc.usr = self.le_usr.text()
        blc.passwd = self.le_passwd.text()
        blc.db = self.le_db.text()
        self.ts1.initserverinfo(blc.host, blc.port, blc.usr, blc.passwd,
                                blc.db)

    def openaboat(self):  #######关于菜单的弹窗内容
        self.wid1 = QMainWindow()
        self.wid1.setWindowTitle('关于')
        self.wid1.setGeometry(300, 300, 300, 300)
        self.wid1.setWindowIcon(self.icon_aboat)
        reviewEdit = QTextEdit(self.wid1)
        reviewEdit.setGeometry(0, 0, 300, 300)
        self.wid1.setFixedSize(self.wid1.width(), self.wid1.height())
        reviewEdit.setPlainText(blc.text_about)
        reviewEdit.setReadOnly(True)
        self.wid1.show()

    def openaurl(self):
        QDesktopServices.openUrl(
            QtCore.QUrl('https://github.com/trz0332/bmsreport'))

    def openhelp(self):  ##帮助菜单的弹窗内容
        if path.exists(
                "help.txt"):  #判断help.txt是否存在,如果存在获取帮助文本里面的内容,填充到文本编辑控件显示
            with open('help.txt', 'r') as fb:
                blc.text_help = fb.read()
        else:
            with open('help.txt',
                      'a') as fb:  #如果帮助文本不存下,从默认的帮助变量获取文本,保存到help.txt
                fb.write(blc.text_help)
        self.wid = QMainWindow()
        self.wid.setWindowTitle('帮助')  #帮助窗口标题
        self.wid.setGeometry(300, 300, 600, 400)  #帮助窗口大小
        self.wid.setWindowIcon(self.icon_help)  #帮助窗口图标
        self.reviewEdit = QTextEdit(self.wid)  #定义一个文本编辑控件
        self.reviewEdit.setGeometry(0, 0, 600, 400)  #设置文本编辑控件大小
        self.wid.setFixedSize(self.wid.width(),
                              self.wid.height())  #设置固定大小不允许改变
        self.reviewEdit.setPlainText(blc.text_help)  #帮助文本的内容填入到文本编辑框
        self.reviewEdit.setReadOnly(True)  #制度模式
        self.wid.show()  #展示窗口

    def saveconfig(self):  #保存配置到config.ini
        config.set('server', 'host', self.le_host.text())
        config.set('server', 'port', self.le_port.text())
        config.set('server', 'user', self.le_usr.text())
        config.set('server', 'passwd', self.le_passwd.text())
        config.set('server', 'db', self.le_db.text())
        config.set('sheet_day', 'sjl', self.ts1.sjl.text())
        config.set('sheet_day', 'gzh', self.ts1.gzh.text())
        config.set('sheet_day', 'cj', str(self.ts1.jsComboBox.currentIndex()))
        config.set('sheet_day', 'mode',
                   str(self.ts1.js2ComboBox.currentIndex()))
        config.set('sheet_day', 'filename', str(self.ts1.qtfile.text()))
        with open("config.ini", "w") as fh:
            config.write(fh)
        QMessageBox.information(self, "信息", "配置文件保存成功", QMessageBox.Yes)
Exemple #11
0
        #except:
        except BaseException as e:
            print("Error")

            from stopeight.analyzer import file
            from os.path import expanduser,join
            file._write(_DATA['MyScribble'].INPUT,join(expanduser("~"),_LOGDIR),self._identify(_DATA['MyScribble']),time)

            _DATA['MyScribble'].INPUT= []
            _DATA['MyScribble'].OUTPUT= []
        _DATA['MyScribble'].clearImage()
        _DATA['MyScribble'].drawData(_DATA['MyScribble'].INPUT,Qt.blue)
        _DATA['MyScribble'].drawData(_DATA['MyScribble'].OUTPUT,Qt.red)
        log.info("Size after call: Input "+str(len(_DATA['MyScribble'].INPUT))+", Output "+str(len(_DATA['MyScribble'].OUTPUT)))
            

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    window = QMainWindow()
    window.setWindowTitle("Editor")
    toolbox = QToolBar()

    for module in _DATA['Module_Name']:
        algo_box = Algorithm(module)
        toolbox.addWidget(algo_box)

    window.addToolBar(toolbox)
    window.setCentralWidget(MyScribble())
    window.show()
    sys.exit(app.exec_())
Exemple #12
0
def main(icon_spec):
    app = QApplication(sys.argv)

    main_window = QMainWindow()

    def sigint_handler(*args):
        main_window.close()
    signal.signal(signal.SIGINT, sigint_handler)
    # the timer enables triggering the sigint_handler
    signal_timer = QTimer()
    signal_timer.start(100)
    signal_timer.timeout.connect(lambda: None)

    tool_bar = QToolBar()
    main_window.addToolBar(Qt.TopToolBarArea, tool_bar)

    table_view = QTableView()
    table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
    table_view.setSelectionMode(QAbstractItemView.SingleSelection)
    table_view.setSortingEnabled(True)
    main_window.setCentralWidget(table_view)

    proxy_model = QSortFilterProxyModel()
    proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
    proxy_model.setFilterKeyColumn(1)
    table_view.setModel(proxy_model)
    proxy_model.layoutChanged.connect(table_view.resizeRowsToContents)

    item_model = QStandardItemModel()
    proxy_model.setSourceModel(item_model)

    # get all icons and their available sizes
    icons = []
    all_sizes = set([])
    for context, icon_names in icon_spec:
        for icon_name in icon_names:
            icon = QIcon.fromTheme(icon_name)
            sizes = []
            for size in icon.availableSizes():
                size = (size.width(), size.height())
                sizes.append(size)
                all_sizes.add(size)
            sizes.sort()
            icons.append({
                'context': context,
                'icon_name': icon_name,
                'icon': icon,
                'sizes': sizes,
            })
    all_sizes = list(all_sizes)
    all_sizes.sort()

    # input field for filter
    def filter_changed(value):
        proxy_model.setFilterRegExp(value)
        table_view.resizeRowsToContents()
    filter_line_edit = QLineEdit()
    filter_line_edit.setMaximumWidth(200)
    filter_line_edit.setPlaceholderText('Filter name')
    filter_line_edit.setToolTip('Filter name optionally using regular expressions (' + QKeySequence(QKeySequence.Find).toString() + ')')
    filter_line_edit.textChanged.connect(filter_changed)
    tool_bar.addWidget(filter_line_edit)

    # actions to toggle visibility of available sizes/columns 
    def action_toggled(index):
        column = 2 + index
        table_view.setColumnHidden(column, not table_view.isColumnHidden(column))
        table_view.resizeColumnsToContents()
        table_view.resizeRowsToContents()
    signal_mapper = QSignalMapper()
    for i, size in enumerate(all_sizes):
        action = QAction('%dx%d' % size, tool_bar)
        action.setCheckable(True)
        action.setChecked(True)
        tool_bar.addAction(action)
        action.toggled.connect(signal_mapper.map)
        signal_mapper.setMapping(action, i)
        # set tool tip and handle key sequence
        tool_tip = 'Toggle visibility of column'
        if i < 10:
            digit = ('%d' % (i + 1))[-1]
            tool_tip += ' (%s)' % QKeySequence('Ctrl+%s' % digit).toString()
        action.setToolTip(tool_tip)
    signal_mapper.mapped.connect(action_toggled)

    # label columns
    header_labels = ['context', 'name']
    for width, height in all_sizes:
        header_labels.append('%dx%d' % (width, height))
    item_model.setColumnCount(len(header_labels))
    item_model.setHorizontalHeaderLabels(header_labels)

    # fill rows
    item_model.setRowCount(len(icons))
    for row, icon_data in enumerate(icons):
        # context
        item = QStandardItem(icon_data['context'])
        item.setFlags(item.flags() ^ Qt.ItemIsEditable)
        item_model.setItem(row, 0, item)
        # icon name
        item = QStandardItem(icon_data['icon_name'])
        item.setFlags(item.flags() ^ Qt.ItemIsEditable)
        item_model.setItem(row, 1, item)
        for index_in_all_sizes, size in enumerate(all_sizes):
            column = 2 + index_in_all_sizes
            if size in icon_data['sizes']:
                # icon as pixmap to keep specific size
                item = QStandardItem('')
                pixmap = icon_data['icon'].pixmap(size[0], size[1])
                item.setData(pixmap, Qt.DecorationRole)
                item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                item_model.setItem(row, column, item)
            else:
                # single space to be sortable against icons
                item = QStandardItem(' ')
                item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                item_model.setItem(row, column, item)

    table_view.resizeColumnsToContents()
    # manually set row heights because resizeRowsToContents is not working properly
    for row, icon_data in enumerate(icons):
        if len(icon_data['sizes']) > 0:
            max_size = icon_data['sizes'][-1]
            table_view.setRowHeight(row, max_size[1])

    # enable focus find (ctrl+f) and toggle columns (ctrl+NUM)
    def main_window_keyPressEvent(self, event, old_keyPressEvent=QMainWindow.keyPressEvent):
        if event.matches(QKeySequence.Find):
            filter_line_edit.setFocus()
            return
        if event.modifiers() == Qt.ControlModifier and event.key() >= Qt.Key_0 and event.key() <= Qt.Key_9:
            index = event.key() - Qt.Key_1
            if event.key() == Qt.Key_0:
                index += 10
            action = signal_mapper.mapping(index)
            if action:
                action.toggle()
                return
        old_keyPressEvent(self, event)
    main_window.keyPressEvent = MethodType(main_window_keyPressEvent, table_view)

    # enable copy (ctrl+c) name of icon to clipboard
    def table_view_keyPressEvent(self, event, old_keyPressEvent=QTableView.keyPressEvent):
        if event.matches(QKeySequence.Copy):
            selection_model = self.selectionModel()
            if selection_model.hasSelection():
                index = selection_model.selectedRows()[0]
                source_index = self.model().mapToSource(index)
                item = self.model().sourceModel().item(source_index.row(), 1)
                icon_name = item.data(Qt.EditRole)
                app.clipboard().setText(icon_name.toString())
                return
        old_keyPressEvent(self, event)
    table_view.keyPressEvent = MethodType(table_view_keyPressEvent, table_view)

    main_window.showMaximized()
    return app.exec_()
#Criando um objeto do incone Qicon
icone = QIcon()
#adicionando a imagem do icone
icone.addFile("../img/exit.png")
#Criando um botao para a barra de ferramenteas
tb_sair = QToolButton()
#Setando imagem
tb_sair.setIcon(icone)
tb_sair.clicked.connect(QApplication.instance().quit)

#criando a barra de ferramentas
barra = QToolBar()
#Adicionando o botão na barra de ferramenteas
barra.addWidget(tb_sair)

jan = QMainWindow()
jan.setGeometry(50, 50, 250, 250)
jan.setWindowTitle("Minha Janela")
jan.setWindowIcon(QIcon("../img/teste.png"))
jan.statusBar().showMessage("Mensagem")
#Adicionando a barra de ferramentas na janela
jan.addToolBar(barra)

b = QPushButton("Tchau", jan)
b.move(100, 100)
b.clicked.connect(QApplication.instance().quit)
b.setToolTip("Se clicar irá sair")

jan.show()
sys.exit(a.exec_())
class Main(QThread):
    '''
    A base class for measurement programs. Users can make a measurement program by inheriting this class.
    
    Notes:
         This class has a graphical user interface which includes a toolbar and the widget made by a user.
        Here, we call the thread where this class's instance lives 'main' thread.
        The user's code is to be written in 'run' method and executed in another thread. We call this one 'run' thread.
        
         Usually, we cannot call a function of a widget in another thread from other thread. 
        To realize this, we use pyqtSignal and Queue object. 
        When a user want to get a value of a widget of GUI in 'run' thread, they need to call 'call' method, handing out 
        the widget and arguments. Then, '__callSignal' is emitted and '__call' method is triggered in 'main' thread. The 
        result of the function is pushed to 'result' queue by 'main' thread. This result is popped by 'run' thread and 
        finally returned as the return value of 'call' method.
        
    Refs:
        ~/overview.png
    '''

    __callSignal = pyqtSignal(
        object, tuple, dict
    )  # Emitted when a user call a function of a widget by 'call' method

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

        # Declaration of instance variables
        self.__initUI(
        )  # Make user interface. Instance variables are declared in this method too
        self.que = Queue()  # Connect between main and graph drawing process
        self.p = Process(target=Graph.initGraphContainer,
                         args=(self.que, ))  # Graph drawing process
        self.result = Queue(
        )  # Queue to put a result of a function called in the thread in which itself exists

        self.finished.connect(self.__finalize)
        self.__callSignal.connect(self.__call)

        self.running = False  # Flag which determins whether run method is still running or not
        self.p.start()

    def __initUI(self):
        # Make the main window
        self.mw = QMainWindow()
        self.scroll = QScrollArea()
        self.mw.setCentralWidget(self.scroll)

        self.toolbar = MyToolBar()
        self.toolbar.exeAction.triggered.connect(self.__exePressed)
        self.toolbar.stopAction.triggered.connect(self.__stopPressed)
        self.toolbar.exitAction.triggered.connect(self.__exitPressed)
        self.toolbar.settingAction.triggered.connect(self.__settingPressed)
        self.toolbar.setState(MyToolBar.READY)
        self.mw.addToolBar(self.toolbar)

        #place the window to the left of the screen
        screen = QDesktopWidget().availableGeometry()
        height = screen.height()
        width = screen.width() / 2
        self.mw.setGeometry(0, 40, width, height)
        self.mw.setWindowIcon(QIcon(kuchinawa.ICONPATH))
        self.mw.setWindowTitle(kuchinawa.KUCHINAWA + ' Control Panel')
        self.mw.show()

    def setUI(self, ui):
        '''
        Set a user interface made by QtDesigner to the main window.
        
        Parameters:
            ui: UI_Form
            
        Returns:
            None
        
        '''
        self.widget = QWidget()
        ui.setupUi(self.widget)
        self.scroll.setWidget(self.widget)

    @abstractmethod
    def run(self):
        '''
        The body of a measurement program. Users need to implement this method for their measurements.
        '''
        raise NotImplementedError(
            'This method must be implemented in a subclass.')

    def __exePressed(self):
        # Called when 'exe' button is pressed
        self.toolbar.setState(MyToolBar.RUNNING)
        self.__resetGraphs()
        self.running = True
        self.start()

    def __exitPressed(self):
        # Called when 'exit' button is pressed
        self.__stopPressed()
        self.que.put(Graph.PoisonPill())
        del (self.mw)

    def __settingPressed(self):
        # Called when 'setting' button is pressed
        try:
            self.settingWindow.showNormal()
        except:
            self.settingWindow = QWidget()
            self.settingUi = Setting_extend.My_Ui_Form()
            self.settingUi.setupUi(self.settingWindow)
            self.settingUi.make_interface()
            self.settingWindow.show()

    def __stopPressed(self):
        # Called when 'stop' button is pressed
        self.running = False

    def __finalize(self):
        # Called when 'run' method is finished
        self.toolbar.setState(MyToolBar.READY)
        self.running = False

    def call(self, function, args=None, kwargs=None):
        '''
        Call a function in the thread in which the instance of this class exists.
        
        Paramters:
            function: function
                a function to call
            args: tuple
                positional arguments
            kwargs: dict
                keyward arguments
                
        Returns:
            object
                depends on the function
        '''
        if args == None:
            args = ()
        if kwargs == None:
            kwargs = {}
        self.__callSignal.emit(function, args, kwargs)
        result = self.result.get()
        return result

    def __call(self, function, args=None, kwargs=None):
        '''
        A slot method for __callSignal. This method is executed when __callSignal is emit and put the return to self.result.
        '''
        if args == None:
            args = ()
        if kwargs == None:
            kwargs = {}
        result = function(*args, **kwargs)
        self.result.put(result)

    def addGraph(self, graph, args=None, kwargs=None, name='Unnamed'):
        '''
        Add a graph to GraphContainer.
        
        Parameters:
            graph: class
                a subclass of Graph.GraphBase
            *args: tuple
                positional arguments to pass to __init__ of 'graph'
            **kwargs: dict
                keyword arguments to pass to __init__ of 'graph'
            name: string
                the window title of the graph
        Returns: Graph.GraphInterface
            the interface to plot data to the graph
        '''
        if args == None:
            args = ()
        if kwargs == None:
            kwargs = {}
        interface = Graph.GraphInterface(self.que, graph, name, *args,
                                         **kwargs)
        return interface

    def __resetGraphs(self):
        '''
        Reset GraphContainer.
        
        Parameters:
            None
        Returns:
            None
        '''
        self.que.put(Graph.ResetSignal())

    def getSaveFile(self, sep='\t', comment='#'):
        '''
        Open a file dialog and return a csv file instance holding the path appointed in the dialog.
        
        Parameters:
            sep: str
                the seperater between values in the csv file
            comment: str
                the header of comment lines
        Returns:
            File.File
        '''
        def fileDialog(parent):
            path, hoge = QFileDialog.getSaveFileName(
                parent, 'select a file to write data to')
            return path

        path = self.call(fileDialog, (self.mw, ))
        file = File.File(path)
        return file
Exemple #15
0
    for i in range(3):
        child1 = QStandardItem("Property")
        child1.setEditable(False)
        child2 = QStandardItem("Value")
        model.appendRow([child1, child2])

    treeView.resize(QSize(100, 100))
    layout = QHBoxLayout()
    layout.addWidget(treeView)
    layout.addWidget(view)
    layout.addWidget(textEdit)

    w.setLayout(layout)
    
    
    mainWindow.menuBar().addMenu("File")
    mainWindow.menuBar().addMenu("Help")

    
    toolBar = QToolBar()
    toolBar.setGeometry(QRect(100, 100, 100, 100))
    toolBar.addAction("Node")
    toolBar.addAction("Edge")

    mainWindow.addToolBar(Qt.LeftToolBarArea, toolBar)
    
    mainWindow.setCentralWidget(w)
    mainWindow.showMaximized()
    
    sys.exit(app.exec_())
Exemple #16
0
class TVMainWindow(QObject):

    # this is the entry point when embedded in tv_browser
    @pyqtSlot(str, str)
    def show_window(self, tv_filename1, tv_filename2):
        self.tv_data_manager.set_tv_data_pair(tv_filename1, tv_filename2)
        self.w.show()

    def __init__(self, signal_want_tv_window=None):
        super(TVMainWindow, self).__init__()

        # use this when embedded in tv_browser
        if signal_want_tv_window:
            signal_want_tv_window.connect(self.show_window)

        # user's preferred TV file path
        self.preferred_tv_dir = os.path.expanduser("~")

        # user's preferred JPG graph path
        self.preferred_graph_dir = os.path.expanduser("~")

        # settings manager
        self.settings_manager = SettingsManager()

        # data manager
        self.tv_data_manager = TVDataManager(
            settings, self.settings_manager.signal_settings_changed)

        # scale manager
        self.tv_scale_manager = TVScaleManager()

        # main window
        self.w = QMainWindow()

        # main window decoration
        self.w.setGeometry(0, 0, 950, 900)
        self.w.setWindowTitle("Texture Vector Similarity Version %s" % VERSION)
        self.w.setWindowIcon(QIcon(window_icon))

        # the graph main widget
        self.tv_graph_widget = TVGraphWidget(
            self.tv_data_manager.signal_data_loaded,
            self.tv_scale_manager.signal_tv_scale_changed)

        # the graph
        self.w.setCentralWidget(self.tv_graph_widget.view)

        # actions
        self.define_actions()

        # sketch checkbox
        self.tv_sketch_cb = TVSketchCB(self.tv_data_manager)

        # toolbar
        self.add_toolbar()

    # actions
    def define_actions(self):
        # open file 1
        self.action_open_file1 = QAction(QIcon("icons/document-open-2.png"),
                                         "&Open1...", self)
        self.action_open_file1.setToolTip("Open File 1")
        self.action_open_file1.triggered.connect(self.select_and_open_file1)

        # open file 2
        self.action_open_file2 = QAction(QIcon("icons/document-open-2.png"),
                                         "&Open2...", self)
        self.action_open_file2.setToolTip("Open File 2")
        self.action_open_file2.triggered.connect(self.select_and_open_file2)

        # settings
        self.action_set_settings = QAction(QIcon("icons/system-settings.png"),
                                           "&Settings...", self)
        self.action_set_settings.setToolTip("Manage threshold settings")
        self.action_set_settings.triggered.connect(self.set_settings)

        # draw sketch
        self.action_toggle_draw_sketch = QAction(
            QIcon("icons/run-build-2.png"), "&Sketch", self)
        self.action_toggle_draw_sketch.setToolTip(
            "Draw fast sketch instead of complete")
        self.action_toggle_draw_sketch.setCheckable(True)
        self.action_toggle_draw_sketch.triggered.connect(
            self.tv_data_manager.toggle_draw_sketch)

        # scale in
        self.action_scale_in = QAction(QIcon("icons/zoom-in-3.png"), "&+",
                                       self)
        self.action_scale_in.setToolTip("Scale in")
        self.action_scale_in.triggered.connect(self.tv_scale_manager.scale_in)

        # scale out
        self.action_scale_out = QAction(QIcon("icons/zoom-out-3.png"), "&-",
                                        self)
        self.action_scale_out.setToolTip("Scale out")
        self.action_scale_out.triggered.connect(
            self.tv_scale_manager.scale_out)

        # scale original size
        self.action_scale_original = QAction(
            QIcon("icons/zoom-original-2.png"), "&1", self)
        self.action_scale_original.setToolTip("Scale to original size")
        self.action_scale_original.triggered.connect(
            self.tv_scale_manager.scale_original)

        # action export graph as image file
        self.action_export_tv_graph = QAction(
            QIcon("icons/document-export-4.png"), "&Export Graph...", self)
        self.action_export_tv_graph.setToolTip(
            "Export similarity graph as image file")
        self.action_export_tv_graph.triggered.connect(
            self.select_and_export_tv_graph)

    # toolbar items
    def add_toolbar(self):
        toolbar = self.w.addToolBar("TV Window Toolbar")
        toolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        toolbar.addAction(self.action_open_file1)
        toolbar.addAction(self.action_open_file2)
        toolbar.addAction(self.action_set_settings)
        toolbar.addWidget(self.tv_sketch_cb.tv_sketch_cb)
        toolbar.addAction(self.action_scale_in)
        toolbar.addAction(self.action_scale_out)
        toolbar.addAction(self.action_scale_original)
        toolbar.addAction(self.action_export_tv_graph)

    ############################################################
    # action handlers
    ############################################################

    # Open TV file1
    @pyqtSlot()
    def select_and_open_file1(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        filename, _ = QFileDialog.getOpenFileName(
            self.w,
            "Open Texture Vector file 1",
            self.preferred_tv_dir,
            "TV files (*.tv);;All Files (*)",
            options=options)

        if filename:
            # remember the preferred path
            head, tail = os.path.split(filename)
            self.preferred_tv_dir = head

            # read the file into tv_data1
            self.tv_data_manager.set_tv_data1(filename)

    # Open TV file2
    @pyqtSlot()
    def select_and_open_file2(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        filename, _ = QFileDialog.getOpenFileName(
            self.w,
            "Open Texture Vector file 2",
            self.preferred_tv_dir,
            "TV files (*.tv);;All Files (*)",
            options=options)

        if filename:
            # remember the preferred path
            head, tail = os.path.split(filename)
            self.preferred_tv_dir = head

            # read the file into tv_data2
            self.tv_data_manager.set_tv_data2(filename)

    # set settings
    @pyqtSlot()
    def set_settings(self):
        wrapper = SettingsDialogWrapper(self.w, self.settings_manager)
        wrapper.exec_()

    def suggested_tv_graph_filename(self):
        try:
            name1 = "_%s" % ntpath.basename(
                self.tv_data_manager.tv_data1["filename"])
        except Exception:
            name1 = ""
        try:
            name2 = "_%s" % ntpath.basename(
                self.tv_data_manager.tv_data2["filename"])
        except Exception:
            name2 = ""

        return "tv_graph%s%s.png" % (name1, name2)

    # export graph as image file
    @pyqtSlot()
    def select_and_export_tv_graph(self):

        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog

        # suggested filename
        suggested_filename = self.suggested_tv_graph_filename()

        filename, _ = QFileDialog.getSaveFileName(
            self.w,
            "Export graph image file",
            os.path.join(self.preferred_graph_dir, suggested_filename),
            "TV graph image files (*.png);;All Files (*)",
            options=options)

        if filename:
            # remember the preferred path
            head, _tail = os.path.split(filename)
            self.preferred_graph_dir = head

            # export the graph as image file
            export_tv_graph(filename, self.tv_graph_widget.scene)
Exemple #17
0
class PythonScriptEditor(QWidget):
    onReload = pyqtSignal()

    def __init__(self, parent, main_window):
        super(PythonScriptEditor, self).__init__(parent)
        self.main_window = main_window
        self.inner = QMainWindow()
        self.setLayout(QVBoxLayout())
        self.setWindowTitle("Script Editor")
        self.editor = CodePlainTextEditor(self.inner)
        self.output = CodePlainTextEditor(self.inner)
        self.output.setReadOnly(True)

        self.pipeline_script = None  #type: PipelineScript

        self.central = QSplitter(Qt.Vertical, self.inner)
        self.central.setMaximumHeight(400)
        self.central.addWidget(self.editor)
        self.central.addWidget(self.output)
        self.highlighter = PythonHighlighter(self.editor.document())

        self.central.setStretchFactor(0, 4)
        self.central.setStretchFactor(1, 1)

        self.inner.setCentralWidget(self.central)
        self.current_file_path = ""
        self.layout().addWidget(self.inner)

        self.m_file = self.inner.menuBar().addMenu("File")
        self.a_new = self.m_file.addAction("New Script")
        self.a_load = self.m_file.addAction("Load")
        self.a_save = self.m_file.addAction("Save")
        self.a_export = self.m_file.addAction("Save As / Export")

        self.a_new.triggered.connect(self.new)
        self.a_load.triggered.connect(partial(self.load, None))
        self.a_save.triggered.connect(partial(self.save, None, False))
        self.a_export.triggered.connect(partial(self.save, None, True))

        if sys.platform == "darwin":
            self.font = QFont("Consolas")
        else:
            self.font = QFont("Lucida Console")
        self.font.setPointSize(10)

        self.toolbar = self.inner.addToolBar("ScriptEditor Toolbar")

        self.a_reload = self.toolbar.addAction("Reload")
        self.a_reload.triggered.connect(self.reload)

        self.editor.setFont(self.font)
        self.editor.setTabStopWidth(
            int(QFontMetricsF(self.editor.font()).width(' ')) * 4)

    def new(self):
        dialog = NewScriptDialog(self, self.main_window)
        dialog.show()
        # self.load("data/default_pipeline.py")
        #
        # self.current_file_path = ""

    def load(self, pipeline: PipelineScript = None):
        if pipeline is None:
            file_path = QFileDialog.getOpenFileName(self, filter="*.py")[0]
            try:
                with open(file_path, "r") as f:
                    script = f.read()

                dialog = NewScriptDialog(self, self.main_window, script)
                dialog.show()
            except Exception as e:
                self.output.setPlainText(traceback.print_exc())
                pass
        else:
            self.pipeline_script = pipeline
            self.editor.setPlainText(pipeline.script)
            self.reload()

    def save(self, file_path=None, save_as=False):
        if self.pipeline_script is None:
            return
        if save_as:
            file_path = QFileDialog.getSaveFileName(self,
                                                    caption="Select Path",
                                                    filter="*.py")[0]
        self.pipeline_script.script = self.editor.toPlainText().replace(
            "\t", "    ")
        self.pipeline_script.save_script(file_path)

    def reload(self):
        self.pipeline_script.script = self.editor.toPlainText().replace(
            "\t", "    ")
        self.pipeline_script.save_script()
        self.editor.setPlainText(self.pipeline_script.script)
        message = self.pipeline_script.import_pipeline()
        self.output.setPlainText(message)
        self.onReload.emit()

    @pyqtSlot(str)
    def print_exception(self, e):
        self.output.setPlainText(e)
        self.raise_()
Exemple #18
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     
     sp = QSizePolicy()
     sp.setHorizontalPolicy(QSizePolicy.Expanding)
     sp.setVerticalPolicy(QSizePolicy.Expanding)
     sp.setVerticalStretch(1)
     
     wb_city_data = load_workbook(filename=r'DSTU-H_B_V.1.1-27_2010.xlsx', 
                                  read_only=True, data_only=True)
     self.__ws_city_I_ser_m_sj = wb_city_data['Лист1']
     self.__ws_city_t_z = wb_city_data['Т2. Температура зовн. пов.']
     
     self.__cityChoice = QComboBox()
     self.__cityChoice.addItems(c[0].value for c in 
                                self.__ws_city_I_ser_m_sj['A6':'A605'] if c[0].value)
     
     self.__q_0Edit = KwNumberEdit(.5)
     self.__V_budEdit = KwNumberEdit(480)
     
     self.__NEdit = QSpinBox()
     self.__NEdit.setRange(1, 999)
     self.__NEdit.setSuffix(' чол')
     self.__NEdit.setValue(6)
     
     self.__t_gvEdit = QSpinBox()
     self.__t_gvEdit.setRange(25, 70)
     self.__t_gvEdit.setSingleStep(5)
     self.__t_gvEdit.setSuffix(' \N{DEGREE CELSIUS}')
     self.__t_gvEdit.setValue(45)
     
     self.__a_gvEdit = QSpinBox()
     self.__a_gvEdit.setRange(15, 99)
     self.__a_gvEdit.setSuffix(' л/добу')
     self.__a_gvEdit.setValue(35)
     
     self.__f_zEdit = KwNumberEdit(.8)
     self.__varthetaEdit = KwNumberEdit(1.7)
     self.__S_0Edit = KwNumberEdit(1.723)
     self.__F_rEdit = KwNumberEdit(1)
     self.__eta_0Edit = KwNumberEdit(0.813)
     self.__ULEdit = KwNumberEdit(4.6)
     self.__aEdit = KwNumberEdit(.007)
     self.__bEdit = KwNumberEdit(1.27E-5)
     self.__c_paEdit = KwNumberEdit(3.16)
     
     self.__P_tpEdit = KwNumberEdit(14.1)
     self.__epsilon_tpEdit = KwNumberEdit(5.5)
     self.__epsilon_elEdit = KwNumberEdit(.88)
     self.__P_elEdit = KwNumberEdit(2.6)
     
     self.__t_co_1Edit = QSpinBox()
     self.__t_co_1Edit.setRange(25, 70)
     self.__t_co_1Edit.setSingleStep(5)
     self.__t_co_1Edit.setSuffix(' \N{DEGREE CELSIUS}')
     self.__t_co_1Edit.setValue(35)
     
     self.__t_co_2Edit = QSpinBox()
     self.__t_co_2Edit.setRange(20, 60)
     self.__t_co_2Edit.setSingleStep(5)
     self.__t_co_2Edit.setSuffix(' \N{DEGREE CELSIUS}')
     self.__t_co_2Edit.setValue(30)
     
     self.__eta_KEdit = KwNumberEdit(.93)
     self.__Q_n_rEdit = KwNumberEdit(35600)
     self.__c_gazEdit = KwNumberEdit(.55)
     self.__c_elEdit = KwNumberEdit(.25)
     
     self.__q_gruEdit = KwNumberEdit(21)
     
     self.__d_gruEdit = QSpinBox()
     self.__d_gruEdit.setRange(5, 99)
     self.__d_gruEdit.setSuffix('  мм')
     self.__d_gruEdit.setValue(25)
     
     self.__l_0_gruEdit = KwNumberEdit(1.7)
     
     calcButton = QPushButton('Визначити')
     calcButton.setObjectName('calcButton')
     
     self.__outputConsoleBrowser = KwConsoleBrowser(setup={'font': {'name': 
           QFont('Hack').family(), 'size': 8}, 'color': 'rgb(255, 255, 255)', 
           'background_color': 'rgba(0, 0, 0, 218)', 'line_wrap': False})
     self.__outputConsoleBrowser.setSizePolicy(sp)
     
     graphWidget = QMainWindow()
     graphWidget.setMinimumWidth(380)
     
     self.__graphCanvas = self.__createFigureCanvas()
     self.__graphNavigationToolbar = NavigationToolbar(self.__graphCanvas, self)
     graphWidget.addToolBar(Qt.TopToolBarArea, self.__graphNavigationToolbar)
     
     graphWidget.setCentralWidget(self.__graphCanvas)
     
     cityLayout = QFormLayout()
     cityLayout.addRow('Місто:', self.__cityChoice)
     
     soGroup = QGroupBox('Для системи опалення (СО):')
     soInputLayout = QFormLayout(soGroup)
     
     soInputLayout.addRow('Питома потужність тепловтрат, q<sub>0</sub>, '
                          'Вт/(м<sup>3</sup>\N{MIDDLE DOT}\N{DEGREE CELSIUS}):', 
                          self.__q_0Edit)
     soInputLayout.addRow("Об'єм будинку по зовнішніх обмірах, V<sub>буд</sub>, "
                          "м<sup>3</sup>:", self.__V_budEdit)
     
     sgvGroup = QGroupBox(u'Для системи гарячого водопостачання (СГК):')
     sgvInputLayout = QFormLayout(sgvGroup)
     sgvInputLayout.addRow('Кількість мешканців у будинку, N:', self.__NEdit)
     sgvInputLayout.addRow('Температура гарячої води, t<sub>гв</sub>:', self.__t_gvEdit)
     sgvInputLayout.addRow('Добова витрата гарячої води на 1 особу, a<sub>гв</sub>:',
                           self.__a_gvEdit)
     
     sgkGroup = QGroupBox('Для системи геліоколекторів (СГК):')
     sgkInputLayout = QFormLayout(sgkGroup)
     sgkInputLayout.addRow('Ступінь заміщення тепловтрат СГВ, f<sub>з</sub>:', self.__f_zEdit)
     sgkInputLayout.addRow('Параметр, \u03D1:', self.__varthetaEdit)
     sgkInputLayout.addRow('Площа 1-го геліоколектора, S<sub>0</sub>, м<sup>2</sup>:',
                           self.__S_0Edit)
     sgkInputLayout.addRow('F<sub>r</sub>:', self.__F_rEdit)
     sgkInputLayout.addRow('Оптичний ККД, \N{GREEK SMALL LETTER ETA}:', self.__eta_0Edit)
     sgkInputLayout.addRow('Коефіцієнт тепловтрат, UL, Вт/(м<sup>2</sup>)'
                           '\N{MIDDLE DOT}\N{DEGREE CELSIUS}):', self.__ULEdit)
     sgkInputLayout.addRow('a:', self.__aEdit)
     sgkInputLayout.addRow('b:', self.__bEdit)
     sgkInputLayout.addRow('c<sub>pa</sub>, кДж/(кг\N{MIDDLE DOT}\N{DEGREE CELSIUS}):',
                           self.__c_paEdit)
     
     tpGroup = QGroupBox('Для теплової помпи (ТП):')
     tpInputLayout = QFormLayout(tpGroup)
     tpInputLayout.addRow('Теплова потужність, P<sub>тп</sub>, кВт:', self.__P_tpEdit)
     tpInputLayout.addRow('Тепловий к.к.д, \N{GREEK SMALL LETTER EPSILON}'
                          '<sub>тп</sub>', self.__epsilon_tpEdit)
     tpInputLayout.addRow('Електричний к.к.д., \N{GREEK SMALL LETTER EPSILON}'
                          '<sub>ел</sub>:', self.__epsilon_elEdit)
     tpInputLayout.addRow('Електрична потужність, P<sub>ел</sub>, кВт:', self.__P_elEdit)
     tpInputLayout.addRow('Т-ра нагрітої води для СО підлоги, t<sub>co 1</sub>:',
                          self.__t_co_1Edit)
     tpInputLayout.addRow('Т-ра охолодженої води для СО підлоги, t<sub>co 2</sub>:',
                          self.__t_co_2Edit)
     tpInputLayout.addRow('К.к.д. згоряння палива, eta_K:', self.__eta_KEdit)
     tpInputLayout.addRow('Нижча теплота згоряння палива, Q<sub>n r</sub>, кДж/м<sup>3</sup>:',
                          self.__Q_n_rEdit)
     tpInputLayout.addRow('Вартість 1 м<sup>3</sup> газу, c<sub>газ</sub>, грн/м<sup>3</sup>:',
                          self.__c_gazEdit)
     tpInputLayout.addRow('Вартість 1 кВт\N{MIDDLE DOT}год, c<sub>ел</sub>, '
                          'грн/м<sup>3</sup>:', self.__c_elEdit)
     
     gruGroup = QGroupBox('Для ґрунту і контуру СО підлоги:')
     gruInputEdit = QFormLayout(gruGroup)
     gruInputEdit.addRow('Питома тепловіддача ґрунту, q<sub>ґр</sub>, '
                         'Вт/м<sup>2</sup>:', self.__q_gruEdit)
     gruInputEdit.addRow('Внутрішній діаметр, d, мм:', self.__d_gruEdit)
     gruInputEdit.addRow('Питома довжина тепловідбору, l<sub>0</sub>, '
                         'м/м<sup>2</sup>:', self.__l_0_gruEdit)
     
     inputScrollArea = QScrollArea()
     inputScrollArea.setWidgetResizable(True)
     inputScrollArea.setSizePolicy(sp)
     
     inputDataPanel = QWidget()
     inputDataLayout = QVBoxLayout(inputDataPanel)
     
     inputDataLayout.addLayout(cityLayout)
     inputDataLayout.addWidget(soGroup)
     inputDataLayout.addWidget(sgvGroup)
     inputDataLayout.addWidget(sgkGroup)
     inputDataLayout.addWidget(tpGroup)
     inputDataLayout.addWidget(gruGroup)
     
     inputScrollArea.setWidget(inputDataPanel)
     
     inputWidget = QWidget()
     inputLayout = QFormLayout(inputWidget)
     #inputLayout.setContentsMargins(0, 0, 0, 0)
     inputLayout.setRowWrapPolicy(QFormLayout.WrapAllRows)
     inputLayout.addRow('Вхідні дані:', inputScrollArea)
     inputLayout.addWidget(calcButton)
     
     consoleViewWidget = QWidget()
     consoleViewLayout = QFormLayout(consoleViewWidget)
     consoleViewLayout.setRowWrapPolicy(QFormLayout.WrapAllRows)
     consoleViewLayout.addRow(u'Результати:', self.__outputConsoleBrowser)
     
     contentSplitter = QSplitter(Qt.Horizontal)
     contentSplitter.setStretchFactor(0, 1)
     contentSplitter.setStretchFactor(1, 0)
     contentSplitter.setSizes([350, 380])
     contentSplitter.setChildrenCollapsible(False)
     
     ioSplitter = QSplitter(Qt.Vertical)
     ioSplitter.setStretchFactor(0, 1)
     ioSplitter.setStretchFactor(1, 0)
     ioSplitter.setSizes([200, 320])
     ioSplitter.setChildrenCollapsible(False)
     ioSplitter.setMinimumWidth(380)
     
     ioSplitter.addWidget(inputWidget)
     ioSplitter.addWidget(consoleViewWidget)
     
     contentSplitter.addWidget(ioSplitter)
     contentSplitter.addWidget(graphWidget)
     
     self.setCentralWidget(contentSplitter)
     
     self.resize(1200, 640)
     
     # <<<
     for inputValueWidget in inputWidget.findChildren((QAbstractSpinBox,
                                                       KwNumberEdit)):
         inputValueWidget.valueChanged.connect(self._reset_output_data)
     
     for inputValueWidget in inputWidget.findChildren(QComboBox):
         inputValueWidget.activated.connect(self._reset_output_data)
     
     calcButton.clicked.connect(self.calc_script)
Exemple #19
0
    action.togglecheck = togglecheck
    action.enabled = enabled
    action.command = command
    action.control = control
    action.status = status

    return action


def get_actions(parent, filepath=None):
    cparser = PuddleConfig()
    if not filepath:
        filepath = shortcut_path
    cparser.filename = filepath
    setting = cparser.data
    actions = []
    for section in cparser.sections():
        if section.startswith('shortcut'):
            values = dict([(str(k), v) for k, v in setting[section].items()])
            actions.append(create_action(parent, **values))
    return actions


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = QMainWindow()
    win.toolbar = win.addToolBar('toolbar')
    loadShortCuts()
    win.show()
    app.exec_()
Exemple #20
0
    def setupUi(self, MainWindow: QtWidgets.QMainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(HmaUi.DEFAULT_WIDTH, HmaUi.DEFAULT_HEIGHT)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # centralwidget
        MainWindow.setCentralWidget(self.centralwidget)
        self.central_layout = QtWidgets.QHBoxLayout()
        self.centralwidget.setLayout(self.central_layout)

        # motion_player
        self.motion_player = mp.MotionPlayer()
#        self.motion_player.setGeometry(QtCore.QRect(0, 0, 960, 720))
        print(self.motion_player.size())
        print(self.motion_player.sizeHint())
        print(self.motion_player.minimumSizeHint())
        self.motion_player.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        self.motion_player.setMouseTracking(False)
        self.motion_player.setObjectName("motion_player")
        self.central_layout.addWidget(self.motion_player)

        # menubar
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1280, 47))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuAnalysis = QtWidgets.QMenu(self.menubar)
        self.menuAnalysis.setObjectName("menuAnalysis")
        MainWindow.setMenuBar(self.menubar)
        self.actionNew = QtWidgets.QAction(MainWindow)
        self.actionNew.setObjectName("actionNew")
        self.actionOpen = QtWidgets.QAction(MainWindow)
        self.actionOpen.setObjectName("actionOpen")
        self.actionImport = QtWidgets.QAction(MainWindow)
        self.actionImport.setObjectName("actionImport")
        self.actionExport = QtWidgets.QAction(MainWindow)
        self.actionExport.setObjectName("actionExport")
        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.menuFile.addAction(self.actionNew)
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionImport)
        self.menuFile.addAction(self.actionExport)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionExit)
        self.menubar.addAction(self.menuFile.menuAction())

        # status bar
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        # tool bar
        self.toolbar = QtWidgets.QToolBar(MainWindow)
        self.toolbar.setObjectName("toolbar")
        MainWindow.addToolBar(self.toolbar)
        self.toolBtn0 = QtWidgets.QAction("toolBtn0", MainWindow)
        self.toolBtn1 = QtWidgets.QAction("toolBtn1", MainWindow)
        self.toolBtn2 = QtWidgets.QAction("toolBtn2", MainWindow)
        self.toolbar.addAction(self.toolBtn0)
        self.toolbar.addAction(self.toolBtn1)
        self.toolbar.addSeparator()
        self.toolbar.addAction(self.toolBtn2)
        #MainWindow.addToolBar("toolbar")
        self.toolbar2 = QtWidgets.QToolBar(MainWindow)
        self.toolbar.setObjectName("toolbar2")
        MainWindow.addToolBar(self.toolbar2)
        self.toolbar2.addAction(self.toolBtn2)

        # dock widgets
        self.dock0 = QtWidgets.QDockWidget("dock0", MainWindow)
        self.dock0.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
        self.dock1 = QtWidgets.QDockWidget("dock1", MainWindow)
        self.dock1.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
        MainWindow.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock0)
        MainWindow.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dock1)
        self.toolbar3 = QtWidgets.QToolBar("toolbar3", MainWindow)
        MainWindow.addToolBar(self.toolbar3)
        self.toolbar3.addAction(self.dock0.toggleViewAction())
        self.toolbar3.addAction(self.dock1.toggleViewAction())

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

        self.connectUi(MainWindow)
Exemple #21
0
from PyQt5.QtWidgets import (QApplication, QMainWindow, QToolBar, QPushButton)

from widgets import BSChartWidget

if __name__ == '__main__':
    app = QApplication([])
    win = QMainWindow()
    win.resize(640, 480)

    bs_chart = BSChartWidget(win)
    win.setCentralWidget(bs_chart)

    toolbar = QToolBar()
    btn_add_pane = QPushButton('add')
    btn_del_pane = QPushButton('del')
    btn_add_pane.clicked.connect(bs_chart.layout.add_pane)
    btn_del_pane.clicked.connect(bs_chart.layout.del_last_pane)
    toolbar.addWidget(btn_add_pane)
    toolbar.addWidget(btn_del_pane)
    win.addToolBar(toolbar)
    win.show()
    app.exec_()
Exemple #22
0
class TabDialog(QDialog):  ##########主界面
    def __init__(self, parent=None):
        super(TabDialog, self).__init__(parent)
        self.creatui()

    def creatui(self):
        self.icon_title = QIcon()
        self.icon_title.addPixmap(QPixmap(":/img/title.ico"), QIcon.Normal,
                                  QIcon.Off)  #标题图表
        self.icon_save = QIcon()
        self.icon_save.addPixmap(QPixmap(":/img/save.ico"), QIcon.Normal,
                                 QIcon.Off)  #保存图表
        self.icon_help = QIcon()
        self.icon_help.addPixmap(QPixmap(":/img/help.ico"), QIcon.Normal,
                                 QIcon.Off)  # 帮助图表
        self.icon_aboat = QIcon()
        self.icon_aboat.addPixmap(QPixmap(":/img/about.ico"), QIcon.Normal,
                                  QIcon.Off)  #关于图表
        self.icon_github = QIcon()
        self.icon_github.addPixmap(QPixmap(":/img/github.ico"), QIcon.Normal,
                                   QIcon.Off)  #关于图表
        self.setWindowTitle('自定义报表程序')
        self.setGeometry(300, 300, 650, 270)
        #self.setFixedSize(self.width(), self.height())
        self.permissionsGroup = QGroupBox("服务器信息")
        self.permissionsLayout = QGridLayout()
        self.setWindowIcon(self.icon_title)
        #########################################
        self.qm = QMainWindow()
        exitAct = QAction(self.icon_save, "保存配置", self.qm)
        exitAct.setShortcut("Ctrl+S")
        exitAct.triggered.connect(self.saveconfig)
        self.toolbar = self.qm.addToolBar("save")
        exitAct1 = QAction(self.icon_help, "帮助", self.qm)
        exitAct1.setShortcut("Ctrl+H")
        exitAct1.triggered.connect(self.openhelp)
        exitAct2 = QAction(self.icon_aboat, "关于", self.qm)
        exitAct2.setShortcut("Ctrl+I")
        exitAct2.triggered.connect(self.openaboat)
        exitAct3 = QAction(self.icon_github, "查看源码", self.qm)
        exitAct3.setShortcut("Ctrl+M")
        exitAct3.triggered.connect(self.openaurl)
        self.toolbar.addAction(exitAct)
        self.toolbar.addAction(exitAct1)
        self.toolbar.addAction(exitAct2)
        self.toolbar.addAction(exitAct3)
        self.updatlabel = QLabel('', self.toolbar)
        self.updatlabel.setOpenExternalLinks(True)
        self.updatlabel.setFixedWidth(150)
        self.updatlabel.move(500, 0)
        ###############第一行###############
        self.permissionsLayout.addWidget(QLabel('数据库', self.permissionsGroup),
                                         1, 0)
        self.le_host = QLineEdit('', self.permissionsGroup)
        #self.le_host.editingFinished.connect(self.initserver)
        self.le_host.setInputMask('000.000.000.000')
        self.le_host.insert(config['server']['host'])
        self.le_host.setFixedWidth(100)
        #print((self.le_host.height(),self.le_host.width()))
        self.permissionsLayout.addWidget(QLabel('端口', self.permissionsGroup),
                                         1, 2)
        self.le_port = QLineEdit('', self.permissionsGroup)
        self.le_port.setInputMask('99999')
        self.le_port.insert(config['server']['port'])
        #self.le_port.editingFinished.connect(self.initserver)
        self.le_port.setFixedWidth(40)
        self.permissionsLayout.addWidget(QLabel('用户名', self.permissionsGroup),
                                         1, 4)
        self.le_usr = QLineEdit('', self.permissionsGroup)
        self.le_usr.insert(config['server']['user'])
        #self.le_usr.editingFinished.connect(self.initserver)
        self.le_usr.setFixedWidth(40)
        self.permissionsLayout.addWidget(QLabel('密码', self.permissionsGroup),
                                         1, 6)
        self.le_passwd = QLineEdit('', self.permissionsGroup)
        self.le_passwd.insert(config['server']['passwd'])
        #self.le_passwd.editingFinished.connect(self.initserver)
        self.le_passwd.setFixedWidth(100)
        self.le_passwd.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.permissionsLayout.addWidget(QLabel('数据库名', self.permissionsGroup),
                                         1, 8)
        self.le_db = QLineEdit('', self.permissionsGroup)
        self.le_db.insert(config['server']['db'])
        self.le_db.setFixedWidth(80)
        #self.le_db.editingFinished.connect(self.initserver)
        ##################################
        self.permissionsLayout.addWidget(QLabel('设备名', self.permissionsGroup),
                                         2, 0)
        self.le_devname = QLineEdit('', self.permissionsGroup)
        self.permissionsLayout.addWidget(self.le_devname, 2, 1, 1, 8)
        self.le_devname.setFixedWidth(600)
        self.qtb1 = QPushButton('查询', self)
        self.permissionsLayout.addWidget(self.qtb1, 2, 9)
        self.qtb1.clicked.connect(self.work)
        ##############################
        self.permissionsLayout.addWidget(self.le_host, 1, 1)
        self.permissionsLayout.addWidget(self.le_port, 1, 3)
        self.permissionsLayout.addWidget(self.le_usr, 1, 5)
        self.permissionsLayout.addWidget(self.le_passwd, 1, 7)
        self.permissionsLayout.addWidget(self.le_db, 1, 9)
        self.permissionsGroup.setLayout(self.permissionsLayout)
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addWidget(self.qm)
        self.mainLayout.addWidget(self.permissionsGroup)
        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)

        self.reviewEdit = QTextEdit(self)  #定义一个文本编辑控件
        self.mainLayout.addWidget(self.reviewEdit)
        self.reviewEdit.setPlainText('')  #帮助文本的内容填入到文本编辑框
        self.ts = zldatbase()

    def initserver(self):
        pass

    def openaurl(self):
        pass

    def openaboat(self):
        pass

    def openhelp(self):
        pass

    def work(self):
        self.qtb1.setEnabled(False)
        self.ts.init(self.le_host.text(), int(self.le_port.text()),
                     self.le_usr.text(), self.le_passwd.text(),
                     self.le_db.text())
        tx = self.ts.main(self.le_devname.text())
        self.reviewEdit.setPlainText(tx)
        self.qtb1.setEnabled(True)
        QMessageBox.information(self, "信息", "查询成功", QMessageBox.Yes)

    def saveconfig(self):
        config.set('server', 'host', self.le_host.text())
        config.set('server', 'port', self.le_port.text())
        config.set('server', 'user', self.le_usr.text())
        config.set('server', 'passwd', self.le_passwd.text())
        config.set('server', 'db', self.le_db.text())
        with open("config.ini", "w") as fh:
            config.write(fh)

        QMessageBox.information(self, "信息", "配置文件保存成功", QMessageBox.Yes)
Exemple #23
0
def main(icon_spec):
    app = QApplication(sys.argv)

    main_window = QMainWindow()

    def sigint_handler(*args):
        main_window.close()

    signal.signal(signal.SIGINT, sigint_handler)
    # the timer enables triggering the sigint_handler
    signal_timer = QTimer()
    signal_timer.start(100)
    signal_timer.timeout.connect(lambda: None)

    tool_bar = QToolBar()
    main_window.addToolBar(Qt.TopToolBarArea, tool_bar)

    table_view = QTableView()
    table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
    table_view.setSelectionMode(QAbstractItemView.SingleSelection)
    table_view.setSortingEnabled(True)
    main_window.setCentralWidget(table_view)

    proxy_model = QSortFilterProxyModel()
    proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
    proxy_model.setFilterKeyColumn(1)
    table_view.setModel(proxy_model)
    proxy_model.layoutChanged.connect(table_view.resizeRowsToContents)

    item_model = QStandardItemModel()
    proxy_model.setSourceModel(item_model)

    # get all icons and their available sizes
    icons = []
    all_sizes = set([])
    QIcon.setThemeName('Tango')
    for context, icon_names in icon_spec:
        for icon_name in icon_names:
            icon = QIcon.fromTheme(icon_name)
            sizes = []
            for size in icon.availableSizes():
                size = (size.width(), size.height())
                sizes.append(size)
                all_sizes.add(size)
            sizes.sort()
            icons.append({
                'context': context,
                'icon_name': icon_name,
                'icon': icon,
                'sizes': sizes,
            })
    all_sizes = list(all_sizes)
    all_sizes.sort()

    # input field for filter
    def filter_changed(value):
        proxy_model.setFilterRegExp(value)
        table_view.resizeRowsToContents()

    filter_line_edit = QLineEdit()
    filter_line_edit.setMaximumWidth(200)
    filter_line_edit.setPlaceholderText('Filter name')
    filter_line_edit.setToolTip(
        'Filter name optionally using regular expressions (' +
        QKeySequence(QKeySequence.Find).toString() + ')')
    filter_line_edit.textChanged.connect(filter_changed)
    tool_bar.addWidget(filter_line_edit)

    # actions to toggle visibility of available sizes/columns
    def action_toggled(index):
        column = 2 + index
        table_view.setColumnHidden(column,
                                   not table_view.isColumnHidden(column))
        table_view.resizeColumnsToContents()
        table_view.resizeRowsToContents()

    signal_mapper = QSignalMapper()
    for i, size in enumerate(all_sizes):
        action = QAction('%dx%d' % size, tool_bar)
        action.setCheckable(True)
        action.setChecked(True)
        tool_bar.addAction(action)
        action.toggled.connect(signal_mapper.map)
        signal_mapper.setMapping(action, i)
        # set tool tip and handle key sequence
        tool_tip = 'Toggle visibility of column'
        if i < 10:
            digit = ('%d' % (i + 1))[-1]
            tool_tip += ' (%s)' % QKeySequence('Ctrl+%s' % digit).toString()
        action.setToolTip(tool_tip)
    signal_mapper.mapped.connect(action_toggled)

    # label columns
    header_labels = ['context', 'name']
    for width, height in all_sizes:
        header_labels.append('%dx%d' % (width, height))
    item_model.setColumnCount(len(header_labels))
    item_model.setHorizontalHeaderLabels(header_labels)

    # fill rows
    item_model.setRowCount(len(icons))
    for row, icon_data in enumerate(icons):
        # context
        item = QStandardItem(icon_data['context'])
        item.setFlags(item.flags() ^ Qt.ItemIsEditable)
        item_model.setItem(row, 0, item)
        # icon name
        item = QStandardItem(icon_data['icon_name'])
        item.setFlags(item.flags() ^ Qt.ItemIsEditable)
        item_model.setItem(row, 1, item)
        for index_in_all_sizes, size in enumerate(all_sizes):
            column = 2 + index_in_all_sizes
            if size in icon_data['sizes']:
                # icon as pixmap to keep specific size
                item = QStandardItem('')
                pixmap = icon_data['icon'].pixmap(size[0], size[1])
                item.setData(pixmap, Qt.DecorationRole)
                item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                item_model.setItem(row, column, item)
            else:
                # single space to be sortable against icons
                item = QStandardItem(' ')
                item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                item_model.setItem(row, column, item)

    table_view.resizeColumnsToContents()
    # manually set row heights because resizeRowsToContents is not working properly
    for row, icon_data in enumerate(icons):
        if len(icon_data['sizes']) > 0:
            max_size = icon_data['sizes'][-1]
            table_view.setRowHeight(row, max_size[1])

    # enable focus find (ctrl+f) and toggle columns (ctrl+NUM)
    def main_window_keyPressEvent(self,
                                  event,
                                  old_keyPressEvent=QMainWindow.keyPressEvent):
        if event.matches(QKeySequence.Find):
            filter_line_edit.setFocus()
            return
        if event.modifiers() == Qt.ControlModifier and event.key(
        ) >= Qt.Key_0 and event.key() <= Qt.Key_9:
            index = event.key() - Qt.Key_1
            if event.key() == Qt.Key_0:
                index += 10
            action = signal_mapper.mapping(index)
            if action:
                action.toggle()
                return
        old_keyPressEvent(self, event)

    main_window.keyPressEvent = MethodType(main_window_keyPressEvent,
                                           table_view)

    # enable copy (ctrl+c) name of icon to clipboard
    def table_view_keyPressEvent(self,
                                 event,
                                 old_keyPressEvent=QTableView.keyPressEvent):
        if event.matches(QKeySequence.Copy):
            selection_model = self.selectionModel()
            if selection_model.hasSelection():
                index = selection_model.selectedRows()[0]
                source_index = self.model().mapToSource(index)
                item = self.model().sourceModel().item(source_index.row(), 1)
                icon_name = item.data(Qt.EditRole)
                app.clipboard().setText(icon_name.toString())
                return
        old_keyPressEvent(self, event)

    table_view.keyPressEvent = MethodType(table_view_keyPressEvent, table_view)

    main_window.showMaximized()
    return app.exec_()
class AnalysisTool(QApplication):
    def __init__(self, sys_argv):
        super(App, self).__init__(sys_argv)
        self.build_ui()

    def build_ui(self):
        # build a main GUI window
        self.main_window = QMainWindow()
        self.main_window.setWindowTitle('Analysis tool')
        self.main_window.show()

        self.canvas = pg.ScatterPlotWidget()

        # add a label to the main window
        splitter = QSplitter(self.main_window)
        splitter.addWidget(self.canvas)
        self.main_window.setCentralWidget(splitter)

        # add a toolbar with an action button to the main window
        action = QAction('Open result file', self)
        action.triggered.connect(self.openFile)
        toolbar = QToolBar()
        toolbar.addAction(action)
        self.main_window.addToolBar(toolbar)

        # self.main_window.addToolBar(Qt.BottomToolBarArea,
        # NavigationToolbar(self.canvas, self.main_window))

        # add a status bar to the main window
        self.status_openfile = QLabel("No file open.")
        self.status_data = QLabel("")
        status_bar = QStatusBar()
        status_bar.addWidget(self.status_openfile, 1)
        status_bar.addWidget(self.status_data, 0)
        self.main_window.setStatusBar(status_bar)

        self.result = None
        self.index = 0
        self.plotdata = [[], [], []]
        self.currentData = [[], [], []]

        self.installEventFilter(self)

    def openFile(self):
        resultfilename = QFileDialog.getOpenFileName(
            self.main_window,
            "Select result file",
            filter="Result files (*.pkl)")[0]
        self.result = Result.load(resultfilename)
        self.status_openfile.setText(resultfilename)
        self.status_data.setText("Iterations: " +
                                 str(self.result.iterationCount))

        fields = []
        for p in self.result.metadata["parametermanager"].parameters:
            fields.append((p.name, {}))

        fields.append(("norm", {}))
        self.canvas.setFields(fields)

        self.index = 0
        self.plotNext()

    def eventFilter(self, obj, event):

        if isinstance(
                event,
                QKeyEvent) and event.type() == QEvent.KeyPress and isinstance(
                    obj, QMainWindow):
            if event.key() == Qt.Key_Space:
                self.plotNext()
                return True

        return False

    def plotNext(self):
        if self.result is None:
            return

        if self.index == len(self.result.evaluations):
            return

        data, tag, _ = self.result.evaluations[self.index]

        target = self.result.metadata["target"]
        targetdata = target.getNumpyArray()

        parameterdata = []

        self.plotdata[0].extend(self.currentData[0])
        self.plotdata[1].extend(self.currentData[1])
        self.plotdata[2].extend(self.currentData[2])

        self.currentData = [[], [], []]

        for ev in data:
            parameterdata.append(ev.parameters)

            measurement = ev.getNumpyArrayLike(target)
            residual = measurement - targetdata

            self.currentData[2].append(np.linalg.norm(residual))

        parameterdata = list(map(list, zip(*parameterdata)))

        self.currentData[0] = parameterdata[0]
        self.currentData[1] = parameterdata[1]

        self.canvas.plot(self.plotdata, self.currentData)
        self.index += 1