Beispiel #1
0
Datei: Menu.py Projekt: aayn/laze
    def initMenu(self):
        menu = self.menuBar()
        menu.setNativeMenuBar(False)
        fileMenu = menu.addMenu('&File')
        editMenu = menu.addMenu('&Edit')
        helpMenu = menu.addMenu('&Help')

        self.exitAction = QAction(QIcon('/home/aayn/Development/Python' +
                                        '/PyQt/laze/images/exit.png'),
                                        '&Exit', self)

        self.fontAction = QAction(QIcon('/home/aayn/Development/Python' +
                                        '/PyQt/laze/images/format.png'),
                                        '&Font', self)

        self.openAction = QAction(QIcon('/home/aayn/Development/Python' +
                                        '/PyQt/laze/images/open.png'),
                                        '&Open', self)

        self.saveAction = QAction(QIcon('/home/aayn/Development/Python' +
                                        '/PyQt/laze/images/save_blue.png'),
                                        '&Save', self)
        self.saveAction.setShortcut('Ctrl+S')

        self.exitAction.setStatusTip('Exit')
        self.fontAction.setStatusTip('Font')
        self.saveAction.setStatusTip('Save')
        self.openAction.setStatusTip('Open')
        fileMenu.addAction(self.openAction)
        fileMenu.addAction(self.saveAction)
        fileMenu.addAction(self.exitAction)
        editMenu.addAction(self.fontAction)

        self.exitAction.triggered.connect(qApp.quit)
Beispiel #2
0
    def updatePlotPersoButton(self):
        menu = QMenu(self.mw)

        menus = []
        for i in [self.tr("Main"), self.tr("Secondary"), self.tr("Minor")]:
            m = QMenu(i, menu)
            menus.append(m)
            menu.addMenu(m)

        mpr = QSignalMapper(menu)
        for i in range(self.mw.mdlCharacter.rowCount()):
            a = QAction(self.mw.mdlCharacter.name(i), menu)
            a.setIcon(self.mw.mdlCharacter.icon(i))
            a.triggered.connect(mpr.map)
            mpr.setMapping(a, int(self.mw.mdlCharacter.ID(i)))

            imp = toInt(self.mw.mdlCharacter.importance(i))

            menus[2 - imp].addAction(a)

        # Disabling empty menus
        for m in menus:
            if not m.actions():
                m.setEnabled(False)

        mpr.mapped.connect(self.addPlotPerso)
        self.mw.btnAddPlotPerso.setMenu(menu)
 def addRecentMenu(self, parent_menu):
     ''' List of recently accessed files '''
     recent_menu = parent_menu.addMenu( 'Recent Files' )
     
     for i in range(0, 10):
         tmp = QAction(self)
         tmp.setVisible(False)
         recent_menu.addAction( tmp )
         tmp.triggered.connect( self.open_recent() )
     
     alist = recent_menu.actions()
     #QSettings settings;
     files = self.settings.value('RecentFileList').toStringList()
     a = alist.size()
     b = files.size()
     limit = b
     if a > b:
         limit = a
         
     for i in range(0, limit):
         file = files[i]
         if file.length() > 160:
             file = file.left(40) + ' ... ' + file.right(100)
         alist[i].setText( file )
         alist[i].setData( files[i] )
         alist[i].setVisible( True )
     
     return recent_menu
    def __init__(self, parent=None):
        super().__init__(parent)

        self.zoom_in_action = QAction(self.tr("Zoom in"), self)
        self.zoom_in_action.setShortcut(QKeySequence.ZoomIn)
        self.zoom_in_action.triggered.connect(self.on_zoom_in_action_triggered)
        self.zoom_in_action.setShortcutContext(Qt.WidgetWithChildrenShortcut)
        self.zoom_in_action.setIcon(QIcon.fromTheme("zoom-in"))
        self.addAction(self.zoom_in_action)

        self.zoom_out_action = QAction(self.tr("Zoom out"), self)
        self.zoom_out_action.setShortcut(QKeySequence.ZoomOut)
        self.zoom_out_action.triggered.connect(self.on_zoom_out_action_triggered)
        self.zoom_out_action.setShortcutContext(Qt.WidgetWithChildrenShortcut)
        self.zoom_out_action.setIcon(QIcon.fromTheme("zoom-out"))
        self.addAction(self.zoom_out_action)

        self.redraw_timer = QTimer()
        self.redraw_timer.setSingleShot(True)
        self.redraw_timer.timeout.connect(self.redraw_view)

        self.zoomed.connect(self.on_signal_zoomed)

        self.scene_y_min = float("nan")  # NaN = AutoDetect
        self.scene_y_max = float("nan")  # NaN = AutoDetect

        self.scene_x_zoom_stretch = 1
Beispiel #5
0
	def initUI(self):
		# 状态栏
		self.statusBar().showMessage('Ready') # 状态栏是用来显示状态信息的组件

		# 创建一个抽象动作行为,用于菜单栏、工具栏或自定义快捷键
		exitAction = QAction(QIcon('exit.png'),'&Exit',self) # 设置图标、文本
		exitAction.setShortcut('Ctrl+Q') # 设置快捷键
		exitAction.setStatusTip('Exit application') # 在状态栏显示提示内容
		exitAction.triggered.connect(qApp.quit) # 选中后中断应用

		# 菜单栏
		menubar = self.menuBar() # 创建菜单栏
		fileMenu = menubar.addMenu('&File') # 创建File菜单
		fileMenu.addAction(exitAction) # 增加退出动作为菜单项

		# 工具栏
		self.toolbar = self.addToolBar('Exit') # 创建工具栏
		self.toolbar.addAction(exitAction) # 增加退出动作为工具项

		# 中心组件,文本框
		textEdit = QTextEdit() # 创建文本框
		self.setCentralWidget(textEdit) # 设置文本框为中心组件,自动占据所有剩下的空间

		# 其他设置
		self.setGeometry(300,300,500,400) # 位置、尺寸
		self.setWindowTitle('Menu Toolbar and Statusbar') # 标题
		self.show()
Beispiel #6
0
 def createActions(self, parent=None):
     
     self.lyrics_hyphenate = QAction(parent)
     self.lyrics_dehyphenate = QAction(parent)
     self.lyrics_copy_dehyphenated = QAction(parent)
     
     self.lyrics_hyphenate.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_L))
Beispiel #7
0
class MediaInfo(Plugin):

    Name = 'MediaInfo'

    def __init__(self):
        self.app = Application()

        self.actionMediaInfo = QAction(None, triggered=self.showInfo)
        self.actionMediaInfo.setText("Media Info")

        self.separator = self.app.layout.add_context_separator(MediaCue)
        self.app.layout.add_context_item(self.actionMediaInfo, MediaCue)

    def reset(self):
        self.app.layout.remove_context_item(self.actionMediaInfo)
        self.app.layout.remove_context_item(self.separator)

    def showInfo(self, clicked):
        media_uri = self.app.layout.get_context_cue().media.input_uri()
        if not media_uri:
            QMessageBox.critical(None, 'Error Message', 'Invalid Media!')
        else:
            gst_info = uri_metadata(media_uri)
            info = {"Uri": unquote(gst_info.get_uri())}

            # Audio streams info
            for stream in gst_info.get_audio_streams():
                name = stream.get_stream_type_nick().capitalize()
                info[name] = {"Bitrate": str(stream.get_bitrate() // 1000) +
                              " Kb/s",
                              "Channels": str(stream.get_channels()),
                              "Sample rate": str(stream.get_sample_rate()) +
                              " Hz",
                              "Sample size": str(stream.get_depth()) + " bit"
                              }

            # Video streams info
            for stream in gst_info.get_video_streams():
                name = stream.get_stream_type_nick().capitalize()
                framerate = round(stream.get_framerate_num() /
                                  stream.get_framerate_denom())
                info[name] = {"Height": str(stream.get_height()) + " px",
                              "Width": str(stream.get_width()) + " px",
                              "Framerate": str(framerate)
                              }

            # Media tags
            info["Tags"] = {}
            tags = parse_gst_tag_list(gst_info.get_tags())
            for tag_name in tags:
                if(not str(tags[tag_name]).startswith("<Gst")):
                    info["Tags"][tag_name.capitalize()] = str(tags[tag_name])

            if len(info["Tags"]) == 0:
                info.pop("Tags")

            # Show the dialog
            dialog = InfoDialog(self.app.mainWindow, info,
                                self.app.layout.get_context_cue()['name'])
            dialog.exec_()
Beispiel #8
0
 def setupMenuBar(self):
     self.fileMenu = self.menuBar().addMenu("&File")
     self.dateFormatMenu = self.fileMenu.addMenu("&Date format")
     self.dateFormatGroup = QActionGroup(self)
     for f in self.dateFormats:
         action = QAction(f, self, checkable=True,
                 triggered=self.changeDateFormat)
         self.dateFormatGroup.addAction(action)
         self.dateFormatMenu.addAction(action)
         if f == self.currentDateFormat:
             action.setChecked(True)
             
     self.fileMenu.addAction(self.printAction)
     self.fileMenu.addAction(self.exitAction)
     self.cellMenu = self.menuBar().addMenu("&Cell")
     self.cellMenu.addAction(self.cell_addAction)
     self.cellMenu.addAction(self.cell_subAction)
     self.cellMenu.addAction(self.cell_mulAction)
     self.cellMenu.addAction(self.cell_divAction)
     self.cellMenu.addAction(self.cell_sumAction)
     self.cellMenu.addSeparator()
     self.cellMenu.addAction(self.colorAction)
     self.cellMenu.addAction(self.fontAction)
     self.menuBar().addSeparator()
     self.aboutMenu = self.menuBar().addMenu("&Help")
     self.aboutMenu.addAction(self.aboutSpreadSheet)
Beispiel #9
0
    def createActions(self, parent):
        self.import_any = QAction(parent)
        self.import_musicxml = QAction(parent)
        self.import_midi = QAction(parent)
        self.import_abc = QAction(parent)

        self.import_any.setIcon(icons.get("document-import"))
Beispiel #10
0
def add_action(submenu, label, callback, shortcut=None):
    """Add action to menu"""
    action = QAction(_(label), mw)
    action.triggered.connect(callback)
    if shortcut:
        action.setShortcut(QKeySequence(shortcut))
    submenu.addAction(action)
Beispiel #11
0
    def __init__(self, device_class, ipcon, device_info, override_base_name=None):
        super().__init__(device_class, ipcon, device_info, override_base_name)

        self.start_called = False
        self.has_comcu = True
        self.cbe_bootloader_mode = CallbackEmulator(self.device.get_bootloader_mode,
                                                    None,
                                                    self.cb_bootloader_mode,
                                                    self.increase_error_count)

        self.status_led_off_action = QAction('Off', self)
        self.status_led_off_action.triggered.connect(lambda: self.device.set_status_led_config(device_class.STATUS_LED_CONFIG_OFF))
        self.status_led_on_action = QAction('On', self)
        self.status_led_on_action.triggered.connect(lambda: self.device.set_status_led_config(device_class.STATUS_LED_CONFIG_ON))
        self.status_led_show_heartbeat_action = QAction('Show Heartbeat', self)
        self.status_led_show_heartbeat_action.triggered.connect(lambda: self.device.set_status_led_config(device_class.STATUS_LED_CONFIG_SHOW_HEARTBEAT))
        self.status_led_show_status_action = QAction('Show Status', self)
        self.status_led_show_status_action.triggered.connect(lambda: self.device.set_status_led_config(device_class.STATUS_LED_CONFIG_SHOW_STATUS))

        self.extra_configs = [(0, 'Status LED:', [self.status_led_off_action,
                                                  self.status_led_on_action,
                                                  self.status_led_show_heartbeat_action,
                                                  self.status_led_show_status_action])]

        self.reset_action = QAction('Reset', self)
        self.reset_action.triggered.connect(self.remove_and_reset)

        self.extra_actions = [(0, None, [self.reset_action])]
Beispiel #12
0
class MainWindow(QMainWindow):  
	def __init__(self,parent=None):  
		super(MainWindow,self).__init__(parent)  
		self.setWindowTitle(self.tr("打印图片"))  
       # 创建一个放置图像的QLabel对象imageLabel,并将该QLabel对象设置为中心窗体。 
		self.imageLabel=QLabel()  
		self.imageLabel.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored)  
		self.setCentralWidget(self.imageLabel)  

		self.image=QImage()  
		  
       # 创建菜单,工具条等部件 
		self.createActions()  
		self.createMenus()  
		self.createToolBars()  

       # 在imageLabel对象中放置图像
		if self.image.load("./images/screen.png"):  
			self.imageLabel.setPixmap(QPixmap.fromImage(self.image))  
			self.resize(self.image.width(),self.image.height())  
									
	def createActions(self):  
		self.PrintAction=QAction(QIcon("./images/printer.png"),self.tr("打印"),self)  
		self.PrintAction.setShortcut("Ctrl+P")  
		self.PrintAction.setStatusTip(self.tr("打印"))  
		self.PrintAction.triggered.connect(self.slotPrint) 

	def createMenus(self):  
		PrintMenu=self.menuBar().addMenu(self.tr("打印"))  
		PrintMenu.addAction(self.PrintAction)  

	def createToolBars(self):  
		fileToolBar=self.addToolBar("Print")  
		fileToolBar.addAction(self.PrintAction)  

	def slotPrint(self):  
       # 新建一个QPrinter对象 
		printer=QPrinter()  
       # 创建一个QPrintDialog对象,参数为QPrinter对象 
		printDialog=QPrintDialog(printer,self)  

		'''
       判断打印对话框显示后用户是否单击“打印”按钮,若单击“打印”按钮,
       则相关打印属性可以通过创建QPrintDialog对象时使用的QPrinter对象获得,
       若用户单击“取消”按钮,则不执行后续的打印操作。 
		''' 		
		if printDialog.exec_():  
           # 创建一个QPainter对象,并指定绘图设备为一个QPrinter对象。
			painter=QPainter(printer)  
			# 获得QPainter对象的视口矩形
			rect=painter.viewport()  
			# 获得图像的大小
			size=self.image.size()  
			# 按照图形的比例大小重新设置视口矩形
			size.scale(rect.size(),Qt.KeepAspectRatio)  
			painter.setViewport(rect.x(),rect.y(),size.width(),size.height())  
			# 设置QPainter窗口大小为图像的大小
			painter.setWindow(self.image.rect()) 
			# 打印			
			painter.drawImage(0,0,self.image)  
    def initUI(self):
        self.setCentralWidget(QuizWidget(self))

        settings_action = QAction(QIcon(""), "Settings", self)
        settings_action.setShortcut("Ctrl+S")
        settings_action.setStatusTip("Settings")
        settings_action.triggered.connect(self.showSettingsDialog)
        # Load all the questions with all possible forms, tenses and polarities
        # so we have a question to ask at startup.
        settingsDialog = SettingsDialog()
        initial_quiz_data = settingsDialog.getQuizData()
        self.centralWidget().updateQuizData(initial_quiz_data)

        exit_action = QAction(QIcon(""), "Exit", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.setStatusTip("Exit Application")
        exit_action.triggered.connect(qApp.exit)

        menu_bar = self.menuBar()
        menu_bar.setNativeMenuBar(False)
        file_menu = menu_bar.addMenu("&File")
        file_menu.addAction(settings_action)
        file_menu.addAction(exit_action)

        self.setGeometry(300, 300, 600, -1)
        self.setWindowTitle("Japanese Flash Cards")
        self.show()
    def __init__(self, parent=None):
        super(ClearHistoryDialog, self).__init__(parent)

        self.setWindowFlags(Qt.Dialog)

        self.setWindowTitle(tr("Clear Data"))

        closeWindowAction = QAction(self)
        closeWindowAction.setShortcuts(["Esc", "Ctrl+W", "Ctrl+Shift+Del"])
        closeWindowAction.triggered.connect(self.close)
        self.addAction(closeWindowAction)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        label = QLabel(tr("What to clear:"), self)
        self.layout.addWidget(label)
        self.dataType = QComboBox(self)
        self.dataType.addItem(tr("History"))
        self.dataType.addItem(tr("Cookies"))
        self.dataType.addItem(tr("Memory Caches"))
        self.dataType.addItem(tr("Persistent Storage"))
        self.dataType.addItem(tr("Everything"))
        self.layout.addWidget(self.dataType)
        self.toolBar = QToolBar(self)
        self.toolBar.setStyleSheet(common.blank_toolbar)
        self.toolBar.setMovable(False)
        self.toolBar.setContextMenuPolicy(Qt.CustomContextMenu)
        self.layout.addWidget(self.toolBar)
        self.clearHistoryButton = QPushButton(tr("Clear"), self)
        self.clearHistoryButton.clicked.connect(self.clearHistory)
        self.toolBar.addWidget(self.clearHistoryButton)
        self.closeButton = QPushButton(tr("Close"), self)
        self.closeButton.clicked.connect(self.close)
        self.toolBar.addWidget(self.closeButton)
 def createActions(self):
     # action for add new
     #root = QFileInfo(__file__).absoluteFilePath()
     self.newAction = QAction(QIcon('icons'+ os.sep + 'appbar.page.add.png'),"&New",self)
     self.newAction.setShortcut('Ctrl+N')
     self.newAction.setStatusTip("Add new student detail")
     self.newAction.triggered.connect(self.newEvent)
     # action for update
     self.updateAction = QAction(QIcon('icons'+ os.sep + 'appbar.page.edit.png'),"&Modify",self)
     self.updateAction.setShortcut('Ctrl+M')
     self.updateAction.setStatusTip("Modify student detail")
     self.updateAction.triggered.connect(self.modifyEvent)
     # action for delete
     self.deleteAction = QAction(QIcon('icons'+ os.sep + 'appbar.delete.png'),"&Delete",self)
     self.deleteAction.setShortcut('Ctrl+D')
     self.deleteAction.setStatusTip("Delete student detail")
     self.deleteAction.triggered.connect(self.deleteEvent)
     # action for export
     self.exportAction = QAction(QIcon('icons'+ os.sep + 'appbar.export.png'),"&Export",self)
     self.exportAction.setShortcut('Ctrl+E')
     self.exportAction.setStatusTip("Export to CSV")
     self.exportAction.triggered.connect(self.exportEvent)
     #action for exit
     self.exitAction = QAction('&Exit', self)        
     self.exitAction.setShortcut('Ctrl+Q')
     self.exitAction.setStatusTip('Exit application')
     self.exitAction.triggered.connect(qApp.quit)
Beispiel #16
0
    def initUI(self):
        # textEdit
        textEdit = QTextEdit()
        self.setCentralWidget(textEdit)

        # action
        exitAction = QAction(QIcon('web.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)

        # menu
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        # tool bar
        exitToolBar = self.addToolBar('Exit')
        exitToolBar.addAction(exitAction)
        commonToolBar = self.addToolBar('Common')
        commonToolBar.addAction(exitAction)

        # status bar
        self.statusBar().showMessage('Ready')

        # main window
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Main Window')
        self.show()
Beispiel #17
0
    def createActions(self):
        self.openAct = QAction("&Open...", self, shortcut="Ctrl+O",
                triggered=self.open)

        for format in QImageWriter.supportedImageFormats():
            format = str(format)

            text = format.upper() + "..."

            action = QAction(text, self, triggered=self.save)
            action.setData(format)
            self.saveAsActs.append(action)

        self.printAct = QAction("&Print...", self,
                triggered=self.scribbleArea.print_)

        self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q",
                triggered=self.close)

        self.penColorAct = QAction("&Pen Color...", self,
                triggered=self.penColor)

        self.penWidthAct = QAction("Pen &Width...", self,
                triggered=self.penWidth)

        self.clearScreenAct = QAction("&Clear Screen", self, shortcut="Ctrl+L",
                triggered=self.scribbleArea.clearImage)

        self.aboutAct = QAction("&About", self, triggered=self.about)

        self.aboutQtAct = QAction("About &Qt", self,
                triggered=QApplication.instance().aboutQt)
    def addCustomWidget(self, text, widget, group=None, defaultVisibility=True):
        """
        Adds a custom widget to the toolbar.

        `text` is the name that will displayed on the button to switch visibility.
        `widget` is the widget to control from the toolbar.
        `group` is an integer (or any hashable) if the current widget should not
            be displayed all the time. Call `collapsibleDockWidgets.setCurrentGroup`
            to switch to that group and hide other widgets.
        `defaultVisibility` is the default visibility of the item when it is added.
            This allows for the widget to be added to `collapsibleDockWidgets` after
            they've been created but before they are shown, and yet specify their
            desired visibility. Otherwise it creates troubles, see #167 on github:
            https://github.com/olivierkes/manuskript/issues/167.
        """
        a = QAction(text, self)
        a.setCheckable(True)
        a.setChecked(defaultVisibility)
        a.toggled.connect(widget.setVisible)
        widget.setVisible(defaultVisibility)
        # widget.installEventFilter(self)
        b = verticalButton(self)
        b.setDefaultAction(a)
        #b.setChecked(widget.isVisible())
        a2 = self.addWidget(b)
        self.otherWidgets.append((b, a2, widget, group))
Beispiel #19
0
    def initUI(self):
        # definisco le azioni
        exitAction = QAction(QIcon('exit.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        # creo la barra dei menu e aggiungo i menu
        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        # creo la toolbar
        toolbar = QToolBar()
        toolbar.addAction(exitAction)
        self.addToolBar(Qt.RightToolBarArea, toolbar)  # toolbar di default sul lato destro della finestra

        # aggiungo il widget centrale
        self.setCentralWidget(LoginWindow(self))

        # cambio posizione e dimensioni della finestra e ne definisco il titiolo infine la faccio apparire
        self.resize(600, 400)
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        self.setWindowTitle('Main window')
        self.show()

        # imposto la statusbar per scrivere che l'app è pronta
        self.statusBar().showMessage('Ready')
Beispiel #20
0
    def initUI(self, width, height):  # Initialize the window
        self.setToolTip('This is a <b>QWidget</b> widget')

        btn = QPushButton('Button', self)
        btn.setToolTip('This is a <b>QPushButton</b> widget')
        icon = QIcon(os.getcwd() + "/img/fichier_icone_GS.gif")
        btn.setIconSize(QSize(50, 50))
        btn.setIcon(icon)
        btn.move(50, 50)
        btn.clicked.connect(self.close)

        self.setGeometry(self.insets.left(), self.insets.top(),
                         width - (self.insets.left() + self.insets.right()),
                         height - (self.insets.top() + self.insets.bottom()))
        self.setWindowTitle('Graphsound')
        self.setWindowIcon(QIcon(os.getcwd() + '/img/fichier_icone_GS.gif'))

        self.statusBar().showMessage('This is the status bar, we can show logs here')

        exitAction = QAction(QIcon('img/exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        file = open("conf/basicTheme.conf")
        self.styleConf = file.read()
        self.setStyleSheet(self.styleConf)

        self.center()
        self.showMaximized()
Beispiel #21
0
 def addDocument(self, doc):
     a = QAction(self)
     a.setCheckable(True)
     if doc is self.mainwindow().currentDocument():
         a.setChecked(True)
     self._acts[doc] = a
     self.setDocumentStatus(doc)
Beispiel #22
0
 def __init__ (self, parent):
     super().__init__(parent)
     self.search = SearchWidget(self)
     self.search.searched.connect(self.populatelist)
     
     self.nodelist = QListWidget(self)
     self.nodelist.setSortingEnabled(True)
     self.nodelist.setIconSize(QSize(*(FlGlob.mainwindow.style.boldheight,)*2))
     self.nodelist.currentItemChanged.connect(self.selectnode)
     self.nodelist.itemSelectionChanged.connect(self.onselectionchange)
     self.nodelist.itemActivated.connect(self.activatenode)
     self.nodelist.setSelectionMode(QAbstractItemView.ExtendedSelection)
     
     remwidget = QToolBar(self)
     remselected = QAction("Remove Selected", self)
     remselected.setIcon(QIcon.fromTheme("edit-delete"))
     remselected.setToolTip("Remove selected")
     remselected.triggered.connect(self.remselected)
     self.remselaction = remselected
     remtrash = QAction("Remove Trash", self)
     remtrash.setIcon(QIcon.fromTheme("edit-clear"))
     remtrash.setToolTip("Clear all trash")
     remtrash.triggered.connect(self.remtrash)
     self.remtrashaction = remtrash
     remwidget.addAction(remselected)
     remwidget.addAction(remtrash)
     
     layout = QVBoxLayout(self)
     layout.addWidget(self.search)
     layout.addWidget(self.nodelist)
     layout.addWidget(remwidget)
     self.view = None
     self.active = False
     self.setEnabled(False)
Beispiel #23
0
    def view_menu(self):
        """Add a view menu to the menu bar.

        The view menu houses the Playlist, Media Library, Minimalist View, and Media
        Information menu items. The Playlist item toggles the playlist dock into and
        out of view. The Media Library items toggles the media library dock into and
        out of view. The Minimalist View item resizes the window and shows only the
        menu bar and player controls. The Media Information item opens a dialog that
        shows information relevant to the currently playing song.
        """
        self.dock_action = self.playlist_dock.toggleViewAction()
        self.dock_action.setShortcut('CTRL+ALT+P')

        self.library_dock_action = self.library_dock.toggleViewAction()
        self.library_dock_action.setShortcut('CTRL+ALT+L')

        self.minimalist_view_action = QAction('Minimalist View', self)
        self.minimalist_view_action.setShortcut('CTRL+ALT+M')
        self.minimalist_view_action.setCheckable(True)
        self.minimalist_view_action.triggered.connect(self.minimalist_view)

        self.view_media_info_action = QAction('Media Information', self)
        self.view_media_info_action.setShortcut('CTRL+SHIFT+M')
        self.view_media_info_action.triggered.connect(self.media_information_dialog)

        self.view.addAction(self.dock_action)
        self.view.addAction(self.library_dock_action)
        self.view.addSeparator()
        self.view.addAction(self.minimalist_view_action)
        self.view.addSeparator()
        self.view.addAction(self.view_media_info_action)
Beispiel #24
0
    def media_controls(self):
        """Create the bottom toolbar and controls used for media playback."""
        self.addToolBar(Qt.BottomToolBarArea, self.toolbar)
        self.toolbar.setMovable(False)

        play_icon = utilities.resource_filename('mosaic.images', 'md_play.png')
        self.play_action = QAction(QIcon(play_icon), 'Play', self)
        self.play_action.triggered.connect(self.player.play)

        stop_icon = utilities.resource_filename('mosaic.images', 'md_stop.png')
        self.stop_action = QAction(QIcon(stop_icon), 'Stop', self)
        self.stop_action.triggered.connect(self.player.stop)

        previous_icon = utilities.resource_filename('mosaic.images', 'md_previous.png')
        self.previous_action = QAction(QIcon(previous_icon), 'Previous', self)
        self.previous_action.triggered.connect(self.previous)

        next_icon = utilities.resource_filename('mosaic.images', 'md_next.png')
        self.next_action = QAction(QIcon(next_icon), 'Next', self)
        self.next_action.triggered.connect(self.playlist.next)

        repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png')
        self.repeat_action = QAction(QIcon(repeat_icon), 'Repeat', self)
        self.repeat_action.setShortcut('R')
        self.repeat_action.triggered.connect(self.repeat_song)

        self.toolbar.addAction(self.play_action)
        self.toolbar.addAction(self.stop_action)
        self.toolbar.addAction(self.previous_action)
        self.toolbar.addAction(self.next_action)
        self.toolbar.addAction(self.repeat_action)
        self.toolbar.addWidget(self.slider)
        self.toolbar.addWidget(self.duration_label)
Beispiel #25
0
    def playback_menu(self):
        """Add a playback menu to the menu bar.

        The playback menu houses
        """
        self.play_playback_action = QAction('Play', self)
        self.play_playback_action.setShortcut('P')
        self.play_playback_action.triggered.connect(self.player.play)

        self.stop_playback_action = QAction('Stop', self)
        self.stop_playback_action.setShortcut('S')
        self.stop_playback_action.triggered.connect(self.player.stop)

        self.previous_playback_action = QAction('Previous', self)
        self.previous_playback_action.setShortcut('B')
        self.previous_playback_action.triggered.connect(self.previous)

        self.next_playback_action = QAction('Next', self)
        self.next_playback_action.setShortcut('N')
        self.next_playback_action.triggered.connect(self.playlist.next)

        self.playback.addAction(self.play_playback_action)
        self.playback.addAction(self.stop_playback_action)
        self.playback.addAction(self.previous_playback_action)
        self.playback.addAction(self.next_playback_action)
Beispiel #26
0
    def initUI(self):
        textEdit = QTextEdit()
        self.setCentralWidget(textEdit)

        lbl1 = QLabel('PyQt5', self)
        lbl1.move(15,10)
        lbl2 = QLabel('tutorial',self)
        lbl2.move(35, 40)
        lbl3 = QLabel('for Programmers', self)
        lbl3.move(55, 70)

        exitAction = QAction(QIcon('20070420141711640.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(qApp.quit)

        self.exittoolbar = self.addToolBar('FileExit')
        self.exittoolbar.addAction(exitAction)
        self.editbar = self.addToolBar('Edit')
        # self.editbar.addAction(exitAction)

        self.statusBar().showMessage('Ready')
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('Menubar')
        self.show()
Beispiel #27
0
    def __init__(self, action: QtWidgets.QAction):
        super().__init__()
        button = QtWidgets.QPushButton(action.icon(), action.text())
        button.clicked.connect(action.trigger)

        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(button)
Beispiel #28
0
    def addShowActions(self):
        """Adds a submenu giving access to the (other)
        opened viewer documents"""
        mds = self._actionCollection.viewer_document_select
        docs = mds.viewdocs()
        document_actions = {}
        multi_docs = len(docs) > 1
        if self._panel.widget().currentViewdoc():
            current_doc_filename = self._panel.widget().currentViewdoc().filename()

        m = self._menu
        sm = QMenu(m)
        sm.setTitle(_("Show..."))
        sm.setEnabled(multi_docs)
        ag = QActionGroup(m)
        ag.triggered.connect(self._panel.slotShowViewdoc)

        for d in docs:
            action = QAction(sm)
            action.setText(d.name())
            action._document_filename = d.filename()
            # TODO: Tooltips aren't shown by Qt (it seems)
            action.setToolTip(d.filename())
            action.setCheckable(True)
            action.setChecked(d.filename() == current_doc_filename)

            ag.addAction(action)
            sm.addAction(action)

        m.addSeparator()
        m.addMenu(sm)
Beispiel #29
0
    def createActions(self):
        self.openAct = QAction("&Open...", self, shortcut="Ctrl+O",
                triggered=self.open)

        self.printAct = QAction("&Print...", self, shortcut="Ctrl+P",
                enabled=False, triggered=self.print_)

        self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q",
                triggered=self.close)

        self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++",
                enabled=False, triggered=self.zoomIn)

        self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-",
                enabled=False, triggered=self.zoomOut)

        self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S",
                enabled=False, triggered=self.normalSize)

        self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False,
                checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow)

        self.aboutAct = QAction("&About", self, triggered=self.about)

        self.aboutQtAct = QAction("About &Qt", self,
                triggered=QApplication.instance().aboutQt)
Beispiel #30
0
 def createActions(self, parent=None):
     self.engrave_sticky = QAction(parent)
     self.engrave_sticky.setCheckable(True)
     self.engrave_runner = QAction(parent)
     self.engrave_preview = QAction(parent)
     self.engrave_publish = QAction(parent)
     self.engrave_debug = QAction(parent)
     self.engrave_custom = QAction(parent)
     self.engrave_abort = QAction(parent)
     self.engrave_autocompile = QAction(parent)
     self.engrave_autocompile.setCheckable(True)
     self.engrave_show_available_fonts = QAction(parent)
     self.engrave_open_lilypond_datadir = QAction(parent)
     
     self.engrave_preview.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_M))
     self.engrave_publish.setShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_P))
     self.engrave_custom.setShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_M))
     self.engrave_abort.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Pause))
     
     self.engrave_sticky.setIcon(icons.get('pushpin'))
     self.engrave_preview.setIcon(icons.get('lilypond-run'))
     self.engrave_publish.setIcon(icons.get('lilypond-run'))
     self.engrave_debug.setIcon(icons.get('lilypond-run'))
     self.engrave_custom.setIcon(icons.get('lilypond-run'))
     self.engrave_abort.setIcon(icons.get('process-stop'))
Beispiel #31
0
    # QWidget窗口是PyQt5中所有用户界口对象的基本类.我们使用了QWidget默认的构造器.默认的构造器没有父类.一个没有父类的窗口被称为一个window.
    w = MainWindow("https://wx.qq.com/?&lang=zh")
    w = MainWindow("http://58.218.201.54:82/index1.html")
    # show()方法将窗口显示在屏幕上.一个窗口是先在内存中被创建,然后显示在屏幕上的.
    w.show()

    # from PyQt5.QtWidgets import QSystemTrayIcon
    # from PyQt5.QtGui import QIcon
    # 在系统托盘处显示图标
    tp = QSystemTrayIcon(w)
    cur_path = os.path.dirname(os.path.realpath(__file__))
    config_path = os.path.join(cur_path, 'timg.jpeg')
    tp.setIcon(QIcon(config_path))
    # 设置系统托盘图标的菜单
    a1 = QAction('&显示(Show)', triggered=w.show)


    def quitApp():
        QCoreApplication.instance().quit()
        # 在应用程序全部关闭后,TrayIcon其实还不会自动消失,
        # 直到你的鼠标移动到上面去后,才会消失,
        # 这是个问题,(如同你terminate一些带TrayIcon的应用程序时出现的状况),
        # 这种问题的解决我是通过在程序退出前将其setVisible(False)来完成的。
        tp.setVisible(False)




    a2 = QAction('&退出(Exit)', triggered=quitApp)  # 直接退出可以用qApp.quit
    def setup_window(self):
        #Dialogs
        self.Waterfall_Plot = WaterfallPlotter(self)
        self.Waterfall = Waterfall(self)
        self.Waterfall_Widget = QWidget()
        self.Waterfall_Box = QVBoxLayout()
        self.Waterfall_Splitter = QSplitter(QtCore.Qt.Horizontal)
        self.Waterfall_Splitter.addWidget(self.Waterfall)
        self.Waterfall_Splitter.addWidget(self.Waterfall_Plot)
        self.Waterfall_Box.addWidget(self.Waterfall_Splitter)
        self.Waterfall_Widget.setLayout(self.Waterfall_Box)

        self.Spider_Widget = QWidget()
        self.Spider_Box = QVBoxLayout()
        self.Spider_Splitter = QSplitter(QtCore.Qt.Horizontal)
        self.Spider_Plot = SpiderPlotter(self)
        self.Spider = Spider(self)
        self.Spider_Splitter.addWidget(self.Spider)
        self.Spider_Splitter.addWidget(self.Spider_Plot)
        self.Spider_Box.addWidget(self.Spider_Splitter)
        self.Spider_Widget.setLayout(self.Spider_Box)

        self.Swimmer_Widget = QWidget()
        self.Swimmer_Box = QVBoxLayout()
        self.Swimmer_Splitter = QSplitter(QtCore.Qt.Horizontal)
        self.Swimmer_Plot = SwimmerPlotter(self)
        self.Swimmer = Swimmer(self)
        self.Swimmer_Splitter.addWidget(self.Swimmer)
        self.Swimmer_Splitter.addWidget(self.Swimmer_Plot)
        self.Swimmer_Box.addWidget(self.Swimmer_Splitter)
        self.Swimmer_Widget.setLayout(self.Swimmer_Box)

        self.stackedWidget.addWidget(self.Waterfall_Widget)  #0
        self.stackedWidget.addWidget(self.Spider_Widget)  #1
        self.stackedWidget.addWidget(self.Swimmer_Widget)  #2
        self.stackedWidget.hide()

        #Set up toolBar
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)

        importAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, 'images\Download.png')),
            'Import date template', self)
        importAction.triggered.connect(self.import_data)
        importAction.setIconText("Import")
        self.toolBar.addAction(importAction)
        self.toolBar.addSeparator()

        dumpAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, 'images\Rubbish.png')),
            'Import date template', self)
        #dumpAction.triggered.connect(self.dump_data)
        dumpAction.setIconText("Dump data")
        self.toolBar.addAction(dumpAction)
        self.toolBar.addSeparator()

        self.waterfallAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, r'images\waterfall.png')),
            'Waterfall plot', self)
        self.waterfallAction.triggered.connect(self.launch_waterfall)
        self.waterfallAction.setIconText("Waterfall")
        self.waterfallAction.setEnabled(False)
        self.toolBar.addAction(self.waterfallAction)

        self.spiderAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, r'images\spider.png')),
            'Spider plot', self)
        self.spiderAction.triggered.connect(self.launch_spider)
        self.spiderAction.setIconText("Spider")
        self.spiderAction.setEnabled(False)
        self.toolBar.addAction(self.spiderAction)

        self.swimmerAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, r'images\swimmer_stack.png')),
            'Swimmer plot', self)
        self.swimmerAction.triggered.connect(self.launch_spider)
        self.swimmerAction.setIconText("Swimmer")
        self.swimmerAction.setEnabled(False)
        self.toolBar.addAction(self.swimmerAction)
        self.toolBar.addSeparator()

        #Signal interconnections
        self.waterfall_data_signal.connect(
            self.Waterfall.on_waterfall_data_signal)
        self.waterfall_data_signal.connect(
            self.Waterfall_Plot.on_waterfall_data_signal)
        self.Waterfall.general_settings_signal.connect(
            self.Waterfall_Plot.on_general_settings_signal)
class MainWindow(QMainWindow, mainwindow.Ui_MainWindow):

    waterfall_data_signal = QtCore.pyqtSignal(dict)

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.setup_window()

    def setup_window(self):
        #Dialogs
        self.Waterfall_Plot = WaterfallPlotter(self)
        self.Waterfall = Waterfall(self)
        self.Waterfall_Widget = QWidget()
        self.Waterfall_Box = QVBoxLayout()
        self.Waterfall_Splitter = QSplitter(QtCore.Qt.Horizontal)
        self.Waterfall_Splitter.addWidget(self.Waterfall)
        self.Waterfall_Splitter.addWidget(self.Waterfall_Plot)
        self.Waterfall_Box.addWidget(self.Waterfall_Splitter)
        self.Waterfall_Widget.setLayout(self.Waterfall_Box)

        self.Spider_Widget = QWidget()
        self.Spider_Box = QVBoxLayout()
        self.Spider_Splitter = QSplitter(QtCore.Qt.Horizontal)
        self.Spider_Plot = SpiderPlotter(self)
        self.Spider = Spider(self)
        self.Spider_Splitter.addWidget(self.Spider)
        self.Spider_Splitter.addWidget(self.Spider_Plot)
        self.Spider_Box.addWidget(self.Spider_Splitter)
        self.Spider_Widget.setLayout(self.Spider_Box)

        self.Swimmer_Widget = QWidget()
        self.Swimmer_Box = QVBoxLayout()
        self.Swimmer_Splitter = QSplitter(QtCore.Qt.Horizontal)
        self.Swimmer_Plot = SwimmerPlotter(self)
        self.Swimmer = Swimmer(self)
        self.Swimmer_Splitter.addWidget(self.Swimmer)
        self.Swimmer_Splitter.addWidget(self.Swimmer_Plot)
        self.Swimmer_Box.addWidget(self.Swimmer_Splitter)
        self.Swimmer_Widget.setLayout(self.Swimmer_Box)

        self.stackedWidget.addWidget(self.Waterfall_Widget)  #0
        self.stackedWidget.addWidget(self.Spider_Widget)  #1
        self.stackedWidget.addWidget(self.Swimmer_Widget)  #2
        self.stackedWidget.hide()

        #Set up toolBar
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)

        importAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, 'images\Download.png')),
            'Import date template', self)
        importAction.triggered.connect(self.import_data)
        importAction.setIconText("Import")
        self.toolBar.addAction(importAction)
        self.toolBar.addSeparator()

        dumpAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, 'images\Rubbish.png')),
            'Import date template', self)
        #dumpAction.triggered.connect(self.dump_data)
        dumpAction.setIconText("Dump data")
        self.toolBar.addAction(dumpAction)
        self.toolBar.addSeparator()

        self.waterfallAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, r'images\waterfall.png')),
            'Waterfall plot', self)
        self.waterfallAction.triggered.connect(self.launch_waterfall)
        self.waterfallAction.setIconText("Waterfall")
        self.waterfallAction.setEnabled(False)
        self.toolBar.addAction(self.waterfallAction)

        self.spiderAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, r'images\spider.png')),
            'Spider plot', self)
        self.spiderAction.triggered.connect(self.launch_spider)
        self.spiderAction.setIconText("Spider")
        self.spiderAction.setEnabled(False)
        self.toolBar.addAction(self.spiderAction)

        self.swimmerAction = QAction(
            QtGui.QIcon(os.path.join(image_dir, r'images\swimmer_stack.png')),
            'Swimmer plot', self)
        self.swimmerAction.triggered.connect(self.launch_spider)
        self.swimmerAction.setIconText("Swimmer")
        self.swimmerAction.setEnabled(False)
        self.toolBar.addAction(self.swimmerAction)
        self.toolBar.addSeparator()

        #Signal interconnections
        self.waterfall_data_signal.connect(
            self.Waterfall.on_waterfall_data_signal)
        self.waterfall_data_signal.connect(
            self.Waterfall_Plot.on_waterfall_data_signal)
        self.Waterfall.general_settings_signal.connect(
            self.Waterfall_Plot.on_general_settings_signal)

    #Launch functions
    def launch_waterfall(self):
        self.stackedWidget.setCurrentIndex(0)
        self.stackedWidget.show()

    def launch_spider(self):
        self.stackedWidget.setCurrentIndex(1)
        self.stackedWidget.show()

    def launch_swimmer(self):
        self.stackedWidget.setCurrentIndex(2)
        self.stackedWidget.show()

    def import_data(self):
        self.file_path = QFileDialog.getOpenFileName(self,
                                                     "Select Data Template",
                                                     "C:\\")[0]
        if self.file_path == '':
            pass
        else:
            self.data_set = import_plot_data(self.file_path)
            self.waterfall_data_signal.emit(self.data_set['waterfall_data'])
        self.waterfallAction.setEnabled(True)
        self.spiderAction.setEnabled(True)
        self.swimmerAction.setEnabled(True)
Beispiel #34
0
    def draw(self):
        self.HeaderLayout = QHBoxLayout()
        self.HeaderLayout.setContentsMargins(1, 1, 1, 0)
        self.HeaderLayout.setSpacing(0)
        self.CentralLayout.addLayout(self.HeaderLayout)

        self.SettingsButton = \
            QPushButton(QIcon(":resources/icons/settings.svg"), "")
        self.SettingsButton.setIconSize(QSize(20, 20))
        self.SettingsButton.setFixedSize(36, 32)
        self.WikiButton = \
            QPushButton(QIcon(":resources/icons/wiki.svg"), "")
        self.WikiButton.setIconSize(QSize(20, 20))
        self.WikiButton.setFixedSize(36, 32)
        self.MinimizeButton = \
            QPushButton(QIcon(":resources/icons/minimize.svg"), "")
        self.MinimizeButton.setIconSize(QSize(20, 20))
        self.MinimizeButton.setFixedSize(36, 32)
        self.CloseButton = \
            QPushButton(QIcon(":resources/icons/close.svg"), "")
        self.CloseButton.setIconSize(QSize(20, 20))
        self.CloseButton.setFixedSize(36, 32)
        self.HeaderLabel = QLabel("Blender Launcher")
        self.HeaderLabel.setAlignment(Qt.AlignCenter)

        self.HeaderLayout.addWidget(self.SettingsButton, 0, Qt.AlignLeft)
        self.HeaderLayout.addWidget(self.WikiButton, 0, Qt.AlignLeft)
        self.HeaderLayout.addWidget(self.HeaderLabel, 1)
        self.HeaderLayout.addWidget(self.MinimizeButton, 0, Qt.AlignRight)
        self.HeaderLayout.addWidget(self.CloseButton, 0, Qt.AlignRight)

        self.SettingsButton.setProperty("HeaderButton", True)
        self.WikiButton.setProperty("HeaderButton", True)
        self.MinimizeButton.setProperty("HeaderButton", True)
        self.CloseButton.setProperty("HeaderButton", True)
        self.CloseButton.setProperty("CloseButton", True)

        # Tab layout
        self.TabWidget = QTabWidget()
        self.CentralLayout.addWidget(self.TabWidget)

        self.LibraryTab = QWidget()
        self.LibraryTabLayout = QVBoxLayout()
        self.LibraryTabLayout.setContentsMargins(0, 0, 0, 0)
        self.LibraryTab.setLayout(self.LibraryTabLayout)
        self.TabWidget.addTab(self.LibraryTab, "Library")

        self.DownloadsTab = QWidget()
        self.DownloadsTabLayout = QVBoxLayout()
        self.DownloadsTabLayout.setContentsMargins(0, 0, 0, 0)
        self.DownloadsTab.setLayout(self.DownloadsTabLayout)
        self.TabWidget.addTab(self.DownloadsTab, "Downloads")

        self.LibraryToolBox = BaseToolBoxWidget(self)

        self.LibraryStableListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Stable Releases", "Nothing to show yet")
        self.LibraryDailyListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Daily Builds", "Nothing to show yet")
        self.LibraryExperimentalListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Experimental Branches", "Nothing to show yet")
        self.LibraryCustomListWidget = \
            self.LibraryToolBox.add_list_widget(
                "Custom Builds", "Nothing to show yet")
        self.LibraryTab.layout().addWidget(self.LibraryToolBox)

        self.DownloadsToolBox = BaseToolBoxWidget(self)

        self.DownloadsStableListWidget = \
            self.DownloadsToolBox.add_list_widget(
                "Stable Releases", "No new builds available", False)
        self.DownloadsDailyListWidget = \
            self.DownloadsToolBox.add_list_widget(
                "Daily Builds", "No new builds available")
        self.DownloadsExperimentalListWidget = \
            self.DownloadsToolBox.add_list_widget(
                "Experimental Branches", "No new builds available")
        self.DownloadsTab.layout().addWidget(self.DownloadsToolBox)

        self.LibraryToolBox.setCurrentIndex(get_default_library_page())

        # Connect buttons
        self.SettingsButton.clicked.connect(self.show_settings_window)
        self.WikiButton.clicked.connect(lambda: webbrowser.open(
            "https://github.com/DotBow/Blender-Launcher/wiki"))
        self.MinimizeButton.clicked.connect(self.showMinimized)
        self.CloseButton.clicked.connect(self.close)

        self.StatusBar.setFont(self.font)
        self.statusbarLabel = QLabel()
        self.statusbarLabel.setIndent(8)
        self.NewVersionButton = QPushButton()
        self.NewVersionButton.hide()
        self.NewVersionButton.clicked.connect(lambda: webbrowser.open(
            "https://github.com/DotBow/Blender-Launcher/releases/latest"))
        self.statusbarVersion = QLabel(self.app.applicationVersion())
        self.StatusBar.addPermanentWidget(self.statusbarLabel, 1)
        self.StatusBar.addPermanentWidget(self.NewVersionButton)
        self.StatusBar.addPermanentWidget(self.statusbarVersion)

        # Draw library
        self.draw_library()

        # Setup tray icon context Menu
        quit_action = QAction("Quit", self)
        quit_action.triggered.connect(self.quit)
        hide_action = QAction("Hide", self)
        hide_action.triggered.connect(self.close)
        show_action = QAction("Show", self)
        show_action.triggered.connect(self._show)
        launch_favorite_action = QAction(
            QIcon(":resources/icons/favorite.svg"), "Blender", self)
        launch_favorite_action.triggered.connect(self.launch_favorite)

        tray_menu = QMenu()
        tray_menu.setFont(self.font)
        tray_menu.addAction(launch_favorite_action)
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addAction(quit_action)

        # Setup tray icon
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(
            QIcon(taskbar_icon_paths[get_taskbar_icon_color()]))
        self.tray_icon.setToolTip("Blender Launcher")
        self.tray_icon.activated.connect(self.tray_icon_activated)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.messageClicked.connect(self._show)
        self.tray_icon.show()

        # Forse style update
        self.style().unpolish(self.app)
        self.style().polish(self.app)

        # Show window
        if get_launch_minimized_to_tray() is False:
            self._show()
Beispiel #35
0
    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action
class RefNodeSetsWidget(QObject):

    error = pyqtSignal(Exception)
    nodeset_added = pyqtSignal(str)
    nodeset_removed = pyqtSignal(str)

    def __init__(self, view):
        QObject.__init__(self, view)
        self.view = view
        self.model = QStandardItemModel()
        self.view.setModel(self.model)
        self.nodesets = []
        self.server_mgr = None
        self.view.header().setSectionResizeMode(1)

        addNodeSetAction = QAction("Add Reference Node Set", self.model)
        addNodeSetAction.triggered.connect(self.add_nodeset)
        self.removeNodeSetAction = QAction("Remove Reference Node Set",
                                           self.model)
        self.removeNodeSetAction.triggered.connect(self.remove_nodeset)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.view.customContextMenuRequested.connect(self.showContextMenu)
        self._contextMenu = QMenu()
        self._contextMenu.addAction(addNodeSetAction)
        self._contextMenu.addAction(self.removeNodeSetAction)

    @trycatchslot
    def add_nodeset(self):
        path, ok = QFileDialog.getOpenFileName(
            self.view,
            caption="Import OPC UA XML Node Set",
            filter="XML Files (*.xml *.XML)",
            directory=".")
        if not ok:
            return None
        self.import_nodeset(path)

    def import_nodeset(self, path):
        print("IMPORT", path)
        name = os.path.basename(path)
        if name in self.nodesets:
            return
        try:
            self.server_mgr.import_xml(path)
        except Exception as ex:
            self.error.emit(ex)
            raise

        item = QStandardItem(name)
        self.model.appendRow([item])
        self.nodesets.append(name)
        self.view.expandAll()
        self.nodeset_added.emit(path)

    @trycatchslot
    def remove_nodeset(self):
        idx = self.view.currentIndex()
        if not idx.isValid() or idx.row() == 0:
            return

        item = self.model.itemFromIndex(idx)
        name = item.text()
        self.nodesets.remove(name)
        self.model.removeRow(idx.row())
        self.nodeset_removed.emit(name)

    def set_server_mgr(self, server_mgr):
        self.server_mgr = server_mgr
        self.nodesets = []
        self.model.clear()
        self.model.setHorizontalHeaderLabels(['Node Sets'])
        item = QStandardItem("Opc.Ua.NodeSet2.xml")
        item.setFlags(Qt.NoItemFlags)
        self.model.appendRow([item])
        self.view.expandAll()

    def clear(self):
        self.model.clear()

    @trycatchslot
    def showContextMenu(self, position):
        if not self.server_mgr:
            return
        idx = self.view.currentIndex()
        if not idx.isValid() or idx.row() == 0:
            self.removeNodeSetAction.setEnabled(False)
        else:
            self.removeNodeSetAction.setEnabled(True)
        self._contextMenu.exec_(self.view.viewport().mapToGlobal(position))
Beispiel #37
0
    def __init__(self, node, iface_name):
        # Parent
        super(MainWindow, self).__init__()
        self.setWindowTitle('UAVCAN GUI Tool')
        self.setWindowIcon(get_app_icon())

        self._node = node
        self._successive_node_errors = 0
        self._iface_name = iface_name

        self._active_data_type_detector = ActiveDataTypeDetector(self._node)

        self._node_spin_timer = QTimer(self)
        self._node_spin_timer.timeout.connect(self._spin_node)
        self._node_spin_timer.setSingleShot(False)
        self._node_spin_timer.start(10)

        self._node_windows = {}  # node ID : window object

        self._node_monitor_widget = NodeMonitorWidget(self, node)
        self._node_monitor_widget.on_info_window_requested = self._show_node_window

        self._local_node_widget = LocalNodeWidget(self, node)
        self._log_message_widget = LogMessageDisplayWidget(self, node)
        self._dynamic_node_id_allocation_widget = DynamicNodeIDAllocatorWidget(
            self, node, self._node_monitor_widget.monitor)
        self._file_server_widget = FileServerWidget(self, node)

        self._plotter_manager = PlotterManager(self._node)
        self._bus_monitor_manager = BusMonitorManager(self._node, iface_name)
        # Console manager depends on other stuff via context, initialize it last
        self._console_manager = ConsoleManager(self._make_console_context)

        #
        # File menu
        #
        quit_action = QAction(get_icon('sign-out'), '&Quit', self)
        quit_action.setShortcut(QKeySequence('Ctrl+Shift+Q'))
        quit_action.triggered.connect(self.close)

        file_menu = self.menuBar().addMenu('&File')
        file_menu.addAction(quit_action)

        #
        # Tools menu
        #
        show_bus_monitor_action = QAction(get_icon('bus'), '&Bus Monitor',
                                          self)
        show_bus_monitor_action.setShortcut(QKeySequence('Ctrl+Shift+B'))
        show_bus_monitor_action.setStatusTip('Open bus monitor window')
        show_bus_monitor_action.triggered.connect(
            self._bus_monitor_manager.spawn_monitor)

        show_console_action = QAction(get_icon('terminal'),
                                      'Interactive &Console', self)
        show_console_action.setShortcut(QKeySequence('Ctrl+Shift+T'))
        show_console_action.setStatusTip('Open interactive console window')
        show_console_action.triggered.connect(self._show_console_window)

        new_subscriber_action = QAction(get_icon('newspaper-o'), '&Subscriber',
                                        self)
        new_subscriber_action.setShortcut(QKeySequence('Ctrl+Shift+S'))
        new_subscriber_action.setStatusTip('Open subscription tool')
        new_subscriber_action.triggered.connect(lambda: SubscriberWindow.spawn(
            self, self._node, self._active_data_type_detector))

        new_plotter_action = QAction(get_icon('area-chart'), '&Plotter', self)
        new_plotter_action.setShortcut(QKeySequence('Ctrl+Shift+P'))
        new_plotter_action.setStatusTip('Open new graph plotter window')
        new_plotter_action.triggered.connect(
            self._plotter_manager.spawn_plotter)

        show_can_adapter_controls_action = QAction(
            get_icon('plug'), 'CAN &Adapter Control Panel', self)
        show_can_adapter_controls_action.setShortcut(
            QKeySequence('Ctrl+Shift+A'))
        show_can_adapter_controls_action.setStatusTip(
            'Open CAN adapter control panel (if supported by the adapter)')
        show_can_adapter_controls_action.triggered.connect(
            self._try_spawn_can_adapter_control_panel)

        tools_menu = self.menuBar().addMenu('&Tools')
        tools_menu.addAction(show_bus_monitor_action)
        tools_menu.addAction(show_console_action)
        tools_menu.addAction(new_subscriber_action)
        tools_menu.addAction(new_plotter_action)
        tools_menu.addAction(show_can_adapter_controls_action)

        #
        # Panels menu
        #
        panels_menu = self.menuBar().addMenu('&Panels')

        for idx, panel in enumerate(PANELS):
            action = QAction(panel.name, self)
            icon = panel.get_icon()
            if icon:
                action.setIcon(icon)
            if idx < 9:
                action.setShortcut(QKeySequence('Ctrl+Shift+%d' % (idx + 1)))
            action.triggered.connect(
                lambda state, panel=panel: panel.safe_spawn(self, self._node))
            panels_menu.addAction(action)

        #
        # Help menu
        #
        uavcan_website_action = QAction(get_icon('globe'),
                                        'Open UAVCAN &Website', self)
        uavcan_website_action.triggered.connect(
            lambda: QDesktopServices.openUrl(QUrl('http://uavcan.org')))

        show_log_directory_action = QAction(get_icon('pencil-square-o'),
                                            'Open &Log Directory', self)
        show_log_directory_action.triggered.connect(
            lambda: QDesktopServices.openUrl(
                QUrl.fromLocalFile(os.path.dirname(log_file.name))))

        about_action = QAction(get_icon('info'), '&About', self)
        about_action.triggered.connect(lambda: AboutWindow(self).show())

        help_menu = self.menuBar().addMenu('&Help')
        help_menu.addAction(uavcan_website_action)
        help_menu.addAction(show_log_directory_action)
        help_menu.addAction(about_action)

        #
        # Window layout
        #
        self.statusBar().show()

        def make_vbox(*widgets, stretch_index=None):
            box = QVBoxLayout(self)
            for idx, w in enumerate(widgets):
                box.addWidget(w, 1 if idx == stretch_index else 0)
            container = QWidget(self)
            container.setLayout(box)
            container.setContentsMargins(0, 0, 0, 0)
            return container

        def make_splitter(orientation, *widgets):
            spl = QSplitter(orientation, self)
            for w in widgets:
                spl.addWidget(w)
            return spl

        self.setCentralWidget(
            make_splitter(
                Qt.Horizontal,
                make_vbox(self._local_node_widget, self._node_monitor_widget,
                          self._file_server_widget),
                make_splitter(
                    Qt.Vertical, make_vbox(self._log_message_widget),
                    make_vbox(self._dynamic_node_id_allocation_widget,
                              stretch_index=1))))
Beispiel #38
0
    def __init__(self):
        super(window, self).__init__()
        self.setGeometry(50, 50, 500, 500)
        self.setWindowTitle('pyqt5 Tut')
        self.setWindowIcon(QIcon('pic.png'))

        extractAction = QAction('&Go to Home', self)
        extractAction.setShortcut('Ctrl+Q')
        extractAction.setStatusTip('leave the app')
        extractAction.triggered.connect(self.close_application)

        openEditor = QAction('&Editor', self)
        openEditor.setShortcut('Ctrl+E')
        openEditor.setStatusTip('Open Editor')
        openEditor.triggered.connect(self.editor)

        openFile = QAction('&Open File', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open File')
        openFile.triggered.connect(self.file_open)

        saveFile = QAction('&Save File', self)
        saveFile.setShortcut('Ctrl+S')
        saveFile.setStatusTip('Save File')
        saveFile.triggered.connect(self.file_save)

        self.statusBar()

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction)

        fileMenu.addAction(openFile)
        fileMenu.addAction(saveFile)

        editorMenu = mainMenu.addMenu('&Editor')
        editorMenu.addAction(openEditor)

        extractAction = QAction(QIcon('pic.png'), 'flee the scene', self)
        extractAction.triggered.connect(self.close_application)
        self.toolBar = self.addToolBar('extraction')
        self.toolBar.addAction(extractAction)

        cal = QCalendarWidget(self)
        cal.move(500, 200)
        cal.resize(200, 200)

        self.home()
Beispiel #39
0
    def init_menu(self):
        layout_load_act = QAction(tr("MenuFile", "Load saved layout..."), self)
        layout_load_act.setShortcut("Ctrl+O")
        layout_load_act.triggered.connect(self.on_layout_load)

        layout_save_act = QAction(tr("MenuFile", "Save current layout..."),
                                  self)
        layout_save_act.setShortcut("Ctrl+S")
        layout_save_act.triggered.connect(self.on_layout_save)

        sideload_json_act = QAction(tr("MenuFile", "Sideload VIA JSON..."),
                                    self)
        sideload_json_act.triggered.connect(self.on_sideload_json)

        download_via_stack_act = QAction(
            tr("MenuFile", "Download VIA definitions"), self)
        download_via_stack_act.triggered.connect(self.load_via_stack_json)

        load_dummy_act = QAction(tr("MenuFile", "Load dummy JSON..."), self)
        load_dummy_act.triggered.connect(self.on_load_dummy)

        exit_act = QAction(tr("MenuFile", "Exit"), self)
        exit_act.setShortcut("Ctrl+Q")
        exit_act.triggered.connect(qApp.exit)

        file_menu = self.menuBar().addMenu(tr("Menu", "File"))
        file_menu.addAction(layout_load_act)
        file_menu.addAction(layout_save_act)
        file_menu.addSeparator()
        file_menu.addAction(sideload_json_act)
        file_menu.addAction(download_via_stack_act)
        file_menu.addAction(load_dummy_act)
        file_menu.addSeparator()
        file_menu.addAction(exit_act)

        keyboard_unlock_act = QAction(tr("MenuSecurity", "Unlock"), self)
        keyboard_unlock_act.triggered.connect(self.unlock_keyboard)

        keyboard_lock_act = QAction(tr("MenuSecurity", "Lock"), self)
        keyboard_lock_act.triggered.connect(self.lock_keyboard)

        keyboard_reset_act = QAction(
            tr("MenuSecurity", "Reboot to bootloader"), self)
        keyboard_reset_act.triggered.connect(self.reboot_to_bootloader)

        keyboard_layout_menu = self.menuBar().addMenu(
            tr("Menu", "Keyboard layout"))
        keymap_group = QActionGroup(self)
        selected_keymap = self.settings.value("keymap")
        for idx, keymap in enumerate(KEYMAPS):
            act = QAction(tr("KeyboardLayout", keymap[0]), self)
            act.triggered.connect(
                lambda checked, x=idx: self.change_keyboard_layout(x))
            act.setCheckable(True)
            if selected_keymap == keymap[0]:
                self.change_keyboard_layout(idx)
                act.setChecked(True)
            keymap_group.addAction(act)
            keyboard_layout_menu.addAction(act)
        # check "QWERTY" if nothing else is selected
        if keymap_group.checkedAction() is None:
            keymap_group.actions()[0].setChecked(True)

        self.security_menu = self.menuBar().addMenu(tr("Menu", "Security"))
        self.security_menu.addAction(keyboard_unlock_act)
        self.security_menu.addAction(keyboard_lock_act)
        self.security_menu.addSeparator()
        self.security_menu.addAction(keyboard_reset_act)

        self.theme_menu = self.menuBar().addMenu(tr("Menu", "Theme"))
        theme_group = QActionGroup(self)
        selected_theme = self.settings.value("theme")
        for name, _ in [("System", None)] + themes.themes:
            act = QAction(tr("MenuTheme", name), self)
            act.triggered.connect(lambda x, name=name: self.set_theme(name))
            act.setCheckable(True)
            act.setChecked(selected_theme == name)
            theme_group.addAction(act)
            self.theme_menu.addAction(act)
        # check "System" if nothing else is selected
        if theme_group.checkedAction() is None:
            theme_group.actions()[0].setChecked(True)
class GraphicsView(QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)
        self.graphics_scene = QGraphicsScene()
        self.pixmap_item = QGraphicsPixmapItem()
        self.graphics_scene.addItem(self.pixmap_item)
        self.setScene(self.graphics_scene)
        self.image = None
        self.image_max = 255
        self.image_range = 255
        self.window_min, self.window_max = 0, 255
        self.shift = 0
        self.scroll = None
        self.current_language = 'en_GB'
        self.context_menu = QMenu()
        self.make_windowing_optional = False
        if self.make_windowing_optional:
            self.use_windowing_action = QAction(
                QCoreApplication.translate('MainWindow', 'Use Windowing'))
            self.use_windowing_action.setCheckable(True)
            self.use_windowing_action.setChecked(True)
            self.use_windowing_action.toggled.connect(
                self.on_use_windowing_action)
            self.context_menu.addAction(self.use_windowing_action)
        self.reset_window_action = QAction(
            QCoreApplication.translate('MainWindow', 'Reset Window'))
        self.reset_window_action.setCheckable(False)
        self.reset_window_action.triggered.connect(self.on_reset_window_action)
        self.context_menu.addAction(self.reset_window_action)

    def set_image(self, image, update_values=False):
        self.image = np.copy(image)
        if update_values:
            self.update_values_from_image(self.image)
        self.update()
        self.resizeEvent()

    def update_values_from_image(self, image):
        if image.min() < 0:
            self.shift = abs(image.min())
        self.image_max = image.max() + self.shift
        self.image_range = image.max() - image.min() + self.shift
        self.window_min, self.window_max = image.min() + self.shift, image.max(
        ) + self.shift

    def update(self):
        if self.image is None: return
        image = np.interp(np.copy(self.image + self.shift),
                          (self.window_min, self.window_max),
                          (0, 255)).astype(np.uint8)
        self.graphics_scene.removeItem(self.graphics_scene.items()[0])
        self.pixmap_item = QGraphicsPixmapItem(QPixmap(array2qimage(image)))
        self.graphics_scene.addItem(self.pixmap_item)

    def mouseMoveEvent(self, event):
        if self.make_windowing_optional and not self.use_windowing_action.isChecked(
        ):
            return
        window_center = self.image_max * event.pos().y() / self.height()
        half_window_width = 0.5 * self.image_range * event.pos().x(
        ) / self.width()
        self.window_min, self.window_max = window_center + half_window_width * np.array(
            [-1, 1])
        self.update()

    def wheelEvent(self, event):
        if self.scroll is not None:
            delta = np.sign(
                event.angleDelta().y())  # * 0.01 * self.scroll.maximum()
            self.scroll.setValue(self.scroll.value() + delta)

    def resizeEvent(self, event=None):
        self.fitInView(self.pixmap_item.boundingRect(), Qt.KeepAspectRatio)

    def contextMenuEvent(self, event):
        self.context_menu.exec(event.globalPos())

    def on_use_windowing_action(self):
        if not self.use_windowing_action.isChecked():
            self.on_reset_window_action()

    def on_reset_window_action(self):
        self.update_values_from_image(self.image)
        self.update()

    def change_language(self, lang):
        self.reset_window_action.setText(
            QCoreApplication.translate('MainWindow', 'Reset Window'))
        if self.make_windowing_optional:
            self.use_windowing_action.setText(
                QCoreApplication.translate('MainWindow', 'Use Windowing'))
Beispiel #41
0
	def initUI(self):

		""" File Operator """
		exitAction = QAction(QtGui.QIcon('exit.png'), '&종료 (Quit)', self)
		exitAction.setShortcut('Ctrl+Q')
		exitAction.setStatusTip('Exit program')
		exitAction.triggered.connect(qApp.exit)
	
		fileOpenAction = QAction(QtGui.QIcon('exit.png'), '&열기 (Open)', self)
		fileOpenAction.setShortcut('Ctrl+O')
		fileOpenAction.setStatusTip('Open script file')
		fileOpenAction.triggered.connect(self.openFileNameDialog)

		fileSaveAction = QAction(QtGui.QIcon('exit.png'), '&저장 (Save)', self)
		fileSaveAction.setShortcut('Ctrl+S')
		fileSaveAction.setStatusTip('Save current script')
		fileSaveAction.triggered.connect(self.saveFileDialog)

		newFile = QAction("&새 파일 (New File)", self)
		newFile.setShortcut("Ctrl+N")
		newFile.setStatusTip('Open blank script file')
		newFile.triggered.connect(self.newFile)

		""" Connect Operator """
		scanAction = QAction(QtGui.QIcon('exit.png'), '&고정 스캔 (Static scan)', self)
		scanAction.setShortcut('Alt+S')
		scanAction.setStatusTip('(root required) Network scanning with default scanning')
		scanAction.triggered.connect(self.scanNetwork)

		dscanAction = QAction(QtGui.QIcon('exit.png'), '&동적 스캔 (Dynamic scan)', self)
		dscanAction.setShortcut('Alt+D')
		dscanAction.setStatusTip('(root required) Dynamic network scanning')
		dscanAction.triggered.connect(self.scanDNetwork)

		vncAction = QAction(QtGui.QIcon('exit.png'), '&VNC 접속 (Connect VNC server)', self)
		vncAction.setShortcut('Alt+V')
		vncAction.setStatusTip('Connect to vnc server')
		vncAction.triggered.connect(self.vncNetwork)

		transportAction = QAction(QtGui.QIcon('exit.png'), '&파일 전송 (File Transfering)', self)
		transportAction.setShortcut('Alt+T')
		transportAction.setStatusTip('File Transfer to target machine')
		transportAction.triggered.connect(self.transNetwork)

		cmdAction = QAction(QtGui.QIcon('exit.png'), '&명령창     (Command Console)', self)
		cmdAction.setShortcut('Alt+C')
		cmdAction.setStatusTip('Open manual handler console')
		cmdAction.triggered.connect(self.cmdNetwork)

		svrAction = QAction(QtGui.QIcon('exit.png'), '&서버 관리 (Server Management)', self)
		svrAction.setShortcut('Alt+M')
		svrAction.setStatusTip('Open server manager window tab')
		svrAction.triggered.connect(self.createsNetworkManager)


		""" Development Operator """
		compileAction = QAction(QtGui.QIcon('exit.png'), '&컴파일 (Compile)', self)
		compileAction.setShortcut('Ctrl+F5')
		compileAction.setStatusTip('Compile present script')
		compileAction.triggered.connect(self.compileScript)

		showhelpAction = QAction(QtGui.QIcon('exit.png'), '&도움말 (Help)', self)
		showhelpAction.setShortcut('F1')
		showhelpAction.setStatusTip('Help')
		showhelpAction.triggered.connect(self.help)

		""" Menu Bar register """
		menubar = self.menuBar()
		fileMenu = menubar.addMenu('&File')
		fileMenu.addAction(newFile)
		fileMenu.addAction(fileOpenAction)
		fileMenu.addAction(fileSaveAction)
		fileMenu.addAction(exitAction)

		connectMenu = menubar.addMenu('&Connect')
		connectMenu.addAction(scanAction)
		connectMenu.addAction(dscanAction)
		connectMenu.addAction(vncAction)
		connectMenu.addAction(transportAction)
		connectMenu.addAction(transportAction)
		connectMenu.addAction(cmdAction)
		connectMenu.addAction(svrAction)

		develMenu = menubar.addMenu('&Development')
		develMenu.addAction(compileAction)
		develMenu.addAction(showhelpAction)

		self.tab = QTabWidget(self)
		self.setCentralWidget(self.tab)
		self.tab.setTabsClosable(True)
		self.tab.setMovable(True)
		self.tab.tabCloseRequested.connect(self.close_handler)
		
		self.create_log()
		self.createsNetworkManager()
		self.statusBar().showMessage('Ready')			  
		self.setGeometry(300, 300, 500, 500)
		self.setWindowTitle('Pycro')
Beispiel #42
0
def add_simple_menu(name, triggers_by_submenu_name, menubar, window):
    menu = menubar.addMenu(name)
    for subname, action in triggers_by_submenu_name.items():
        a = QAction(subname, window)
        a.triggered.connect(action)
        menu.addAction(a)
Beispiel #43
0
    def initUI(self):

        self.current_dir = 'F:/Desktop2020.1.17/AutoCut/'
        self.font = cv2.FONT_HERSHEY_SIMPLEX

        self.mouse_pos_initial()

        exitAct = QAction(QIcon('quit.jpg'), '&Quit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.triggered.connect(qApp.quit)

        help_contact = QAction('Contact', self)
        help_contact.triggered.connect(self.contact)

        self.menubar = self.menuBar()

        FileMenu = self.menubar.addMenu('&File')
        FileMenu.addAction(exitAct)

        HelpMenu = self.menubar.addMenu('&Help')
        HelpMenu.addAction(help_contact)

        self.read_button = QToolButton()
        self.read_button.setIcon(QIcon(self.current_dir + 'read.png'))
        self.read_button.setToolTip('Read Ctrl+R')
        self.read_button.clicked.connect(self.read)
        self.read_button.setShortcut('Ctrl+R')

        self.draw_shape_action_list = []
        self.draw_shape_list = []
        self.draw_shape_action_list_for_redo = []
        self.draw_shape_count = 1

        self.line_button = QToolButton()
        self.line_button.setIcon(QIcon(self.current_dir + 'line.png'))
        self.line_button.setToolTip('Draw line')
        self.line_button.clicked.connect(self.draw_line)
        self.line_button.setCheckable(True)
        self.draw_shape_line = False
        self.drawing_shape_line = False
        self.show_distance = False

        #        line = Line(0,0,100,100)

        self.eraser_button = QToolButton()
        self.eraser_button.setIcon(QIcon(self.current_dir + 'eraser.png'))
        self.eraser_button.setToolTip('eraser')
        self.eraser_button.clicked.connect(self.erase_shape)
        self.eraser_button.setCheckable(True)
        self.erase = False
        self.drawing_eraser = False

        self.undo_button = QToolButton()
        self.undo_button.setIcon(
            QIcon(self.current_dir + 'undo_gray_opacity.png'))
        self.undo_button.setToolTip('undo  Ctrl+Z')
        self.undo_button.clicked.connect(self.undo_draw)
        self.undo_button.setShortcut('Ctrl+Z')

        self.redo_button = QToolButton()
        self.redo_button.setIcon(
            QIcon(self.current_dir + 'redo_gray_opacity.png'))
        self.redo_button.setToolTip('redo  Ctrl+Y')
        self.redo_button.clicked.connect(self.redo_draw)
        self.redo_button.setShortcut('Ctrl+Y')

        self.clear_button = QToolButton()
        self.clear_button.setIcon(QIcon(self.current_dir + 'clear.png'))
        self.clear_button.setToolTip('clear drawing')
        self.clear_button.clicked.connect(self.clear_draw)

        self.run_button = QToolButton()
        self.run_button.setIcon(QIcon(self.current_dir + 'run.png'))
        self.run_button.setToolTip('Run F5')
        self.run_button.clicked.connect(self.run_cut)
        self.run_button.setShortcut('F5')

        self.repeat_button = QToolButton()
        self.repeat_button.setIcon(QIcon(self.current_dir + 'repeat.png'))
        self.repeat_button.setToolTip('Repeat')
        self.repeat_button.clicked.connect(self.repeat_cut)

        self.toolbar1 = self.addToolBar('Read')
        self.toolbar1.addWidget(self.read_button)

        self.toolbar2 = self.addToolBar('draw')
        self.toolbar2.addWidget(self.line_button)
        self.toolbar2.addWidget(self.undo_button)
        self.toolbar2.addWidget(self.redo_button)
        self.toolbar2.addWidget(self.eraser_button)
        self.toolbar2.addWidget(self.clear_button)

        self.toolbar3 = self.addToolBar('run')
        self.toolbar3.addWidget(self.run_button)
        self.toolbar3.addWidget(self.repeat_button)

        self.toolbar = self.addToolBar(' ')

        self.pixmap = QPixmap()
        self.lbl_main = QLabel(self)
        self.lbl_main.setAlignment(Qt.AlignTop)
        #        self.lbl_main.setAlignment(Qt.AlignCenter)
        self.lbl_main.setPixmap(self.pixmap)

        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.lbl_main)

        self.central_widget = QWidget()

        self.layout = QVBoxLayout(self.central_widget)
        self.setCentralWidget(self.central_widget)
        self.layout.addLayout(self.vbox)

        self.refresh_timer = QTimer()
        self.refresh_timer.timeout.connect(self.refresh_show)

        self.setWindowTitle('Auto Cut')
        self.show()
Beispiel #44
0
    def __init__(self):
        super().__init__()

        # Create Menu bar
        bar = self.menuBar()

        # Create Root Menu
        file = bar.addMenu("File")
        edit = bar.addMenu("Edit")

        # Create Actions for menus
        save_action = QAction("&Save", self)
        save_action.setShortcut("Ctrl+S")

        new_action = QAction("&New", self)
        new_action.setShortcut("Ctrl+N")

        quit_action = QAction("&Quit", self)
        quit_action.setShortcut("Ctrl+Q")

        find_action = QAction("Find", self)

        replace_action = QAction("Replace", self)

        # Add Actions to menus
        file.addAction(new_action)
        file.addAction(save_action)
        file.addAction(quit_action)

        find_menu = edit.addMenu("Find")
        find_menu.addAction(find_action)
        find_menu.addAction(replace_action)

        # Events
        quit_action.triggered.connect(self.quit_trigger)
        file.triggered.connect(self.selected)

        self.setWindowTitle("Menu")
        self.resize(600, 800)

        self.show()
Beispiel #45
0
    def create_format_menu(self, parent=None):
        if self.format_menu is not None:
            self.format_menu.clear()
        else:
            self.format_menu = QMenu("Formats", parent)
        formats = self.get_tcam().get_static_pad("src").query_caps()

        def get_framerates(fmt):
            try:
                rates = fmt.get_value("framerate")
            except TypeError:
                # Workaround for missing GstValueList support in GI
                substr = fmt.to_string()[fmt.to_string().find("framerate="):]
                # try for frame rate lists
                field, values, remain = re.split("{|}", substr, maxsplit=3)
                rates = [x.strip() for x in values.split(",")]
            return rates

        format_dict = {}

        for j in range(formats.get_size()):
            fmt = formats.get_structure(j)
            try:
                format_string = fmt.get_value("format")
                if format_string == "{ RGBx, xRGB, BGRx, xBGR, RGBA, ARGB, BGRA, ABGR }":
                    format_string = "BGRx"
                elif (format_string is None or format_string == "None"
                      or "bayer" in fmt.get_name()):
                    continue

                if format_string not in format_dict:
                    format_dict[format_string] = QMenu(format_string, self)

                width = fmt.get_value("width")
                height = fmt.get_value("height")
                f_str = "{} - {}x{}".format(format_string, width, height)
                if "None" in f_str:
                    continue
                if "range" in format_string:
                    continue
                f_menu = format_dict[format_string].addMenu("{}x{}".format(
                    width, height))

            except TypeError as e:
                log.warning("Could not interpret structure. Omitting.")
                continue

            rates = get_framerates(fmt)
            if rates is None:
                continue
            if type(rates) is Gst.FractionRange:
                continue
            for rate in rates:
                rate = str(rate)
                action = QAction(rate, self)
                action.setToolTip("Set format to '{}'".format(f_str + "@" +
                                                              rate))
                f = "video/x-raw,format={},width={},height={},framerate={}".format(
                    format_string, width, height, rate)
                action.triggered.connect(functools.partial(self.play, f))
                f_menu.addAction(action)

        # do not iterate the dict, but add manually
        # this is neccessary to ensure the order is always correct
        # for key, value in format_dict.items():
        #     self.format_menu.addMenu(value)

        for f in self.format_list:
            try:
                self.format_menu.addMenu(format_dict[f])
            except:
                continue
    def initUI(self):
        menubar = self.menuBar()

        self.textEd = QTextEdit()
        self.textEd.setReadOnly(True)
        font = QFont()
        font.setPointSize(14)
        self.textEd.setFont(font)
        self.setCentralWidget(self.textEd)

        #config menu
        configMenu = menubar.addMenu("config")

        remoteSvrShowAct = QAction("显示远程服务器", self)
        remoteSvrShowAct.triggered.connect(self.remoteSvrShow)
        configMenu.addAction(remoteSvrShowAct)

        remoteSvrConfAct = QAction("配置远程服务器", self)
        remoteSvrConfAct.triggered.connect(self.remoteSvrConf)
        configMenu.addAction(remoteSvrConfAct)
        configMenu.addSeparator()

        localPGShowAct = QAction("浏览本地pgpass文件", self)
        localPGShowAct.triggered.connect(lambda: self.pgpassShow(None))
        configMenu.addAction(localPGShowAct)

        remotePGShowAct = QAction("浏览远程pgpass文件", self)
        remotePGShowAct.triggered.connect(
            lambda: self.pgpassShow(self.dbbk.remoteServer))
        configMenu.addAction(remotePGShowAct)
        configMenu.addSeparator()

        addLocalPGAct = QAction("添加本地pgpass记录", self)
        addLocalPGAct.triggered.connect(lambda: self.addPgpass(None))
        configMenu.addAction(addLocalPGAct)

        addRemotePGAct = QAction("添加远程pgpass记录", self)
        addRemotePGAct.triggered.connect(
            lambda: self.addPgpass(self.dbbk.remoteServer))
        configMenu.addAction(addRemotePGAct)

        #run menu
        optMenu = menubar.addMenu("run")

        backupAct = QAction("数据库备份", self)
        backupAct.triggered.connect(self.dbBackup)
        optMenu.addAction(backupAct)

        restoreAct = QAction("数据库恢复", self)
        restoreAct.triggered.connect(self.dbRestore)
        optMenu.addAction(restoreAct)
        optMenu.addSeparator()

        remoteBkAct = QAction("远程备份", self)
        remoteBkAct.triggered.connect(self.remoteBackup)
        optMenu.addAction(remoteBkAct)
        optMenu.addSeparator()

        structAct = QAction("表结构备份", self)
        structAct.triggered.connect(self.structBackup)
        optMenu.addAction(structAct)

        datasAct = QAction("表数据备份", self)
        datasAct.triggered.connect(self.datasBackup)
        optMenu.addAction(datasAct)
        optMenu.addSeparator()

        tableMenu = QMenu("单个表备份", self)
        optMenu.addMenu(tableMenu)

        tableAct = QAction("表备份", self)
        tableAct.triggered.connect(self.tableBackup)
        tableMenu.addAction(tableAct)

        tableStructAct = QAction("结构备份", self)
        tableStructAct.triggered.connect(self.tableStructBackup)
        tableMenu.addAction(tableStructAct)

        tableDataAct = QAction("数据备份", self)
        tableDataAct.triggered.connect(self.tableDataBackup)
        tableMenu.addAction(tableDataAct)

        self.setGeometry(700, 300, 400, 300)
        self.setWindowTitle('数据库备份工具')
        self.show()
    def __init__(self, parent=None):
        super(VideoWindow, self).__init__(parent)
        self.setWindowTitle("ONI Player")
        self.setWindowIcon(QIcon('images/play.png'))
        self.vsource = None

        class MediaPlayer(QMediaPlayer):
            def __init__(self, parent=None, flags=QMediaPlayer.VideoSurface):
                super(MediaPlayer, self).__init__(parent)
                self.parent = parent

            def frame_step(self, direction):
                frames = list(map(round, self.parent.vsource.track.timecodes))
                if 0 < self.position() < max(frames):
                    dif = [abs(self.position() - x) for x in frames]
                    self.setPosition(frames[dif.index(min(dif)) + direction])

        self.colorMediaPlayer = MediaPlayer(parent=self)
        self.depthMediaPlayer = MediaPlayer(parent=self)

        self.colorVideoWidget = QVideoWidget()
        self.depthVideoWidget = QVideoWidget()

        # spacers for control panel
        self.leftSpacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                          QSizePolicy.Minimum)
        self.rightSpacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding,
                                           QSizePolicy.Minimum)

        # buttom for control panel
        self.backButton = QPushButton()
        self.backButton.setEnabled(False)
        self.backButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekBackward))
        self.backButton.clicked.connect(lambda: self.prev_next_frame(-1))
        self.backButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)
        self.playButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum)

        self.forwardButton = QPushButton()
        self.forwardButton.setEnabled(False)
        self.forwardButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaSeekForward))
        self.forwardButton.clicked.connect(lambda: self.prev_next_frame(1))
        self.forwardButton.setSizePolicy(QSizePolicy.Fixed,
                                         QSizePolicy.Minimum)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
                                      QSizePolicy.Maximum)
        self.colorLabel = QLabel('Color stream')
        self.depthLabel = QLabel('Depth stream')
        self.hframe = QFrame(self)
        self.hframe.setFrameShape(QFrame.HLine)
        self.hframe.setFrameShadow(QFrame.Raised)
        # self.hframe.setLineWidth(1)

        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open movie')
        openAction.triggered.connect(self.openFile)

        # Create exit action
        exitAction = QAction(QIcon('exit.png'), '&Exit', self)  # png!!!
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.exitCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(openAction)
        fileMenu.addAction(exitAction)

        # Create a widget for window contents
        wid = QWidget(self)
        self.setCentralWidget(wid)

        # Create layouts to place inside widget
        controlLayout = QHBoxLayout()
        controlLayout.addSpacerItem(self.leftSpacerItem)
        controlLayout.addWidget(self.backButton)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.forwardButton)
        controlLayout.addSpacerItem(self.rightSpacerItem)

        self.videoLayout = QGridLayout()
        self.videoLayout.setSpacing(10)
        self.videoLayout.addWidget(self.colorLabel, 0, 0, Qt.AlignCenter)
        self.videoLayout.addWidget(self.depthLabel, 0, 1, Qt.AlignCenter)
        self.videoLayout.addWidget(self.colorVideoWidget, 1, 0)
        self.videoLayout.addWidget(self.depthVideoWidget, 1, 1)

        layout = QVBoxLayout()
        layout.addLayout(self.videoLayout)
        layout.addWidget(self.positionSlider)
        layout.addLayout(controlLayout)
        layout.addWidget(self.hframe)
        layout.addWidget(self.errorLabel)

        # Set widget to contain window contents
        wid.setLayout(layout)

        self.colorMediaPlayer.setVideoOutput(self.colorVideoWidget)
        self.colorMediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.colorMediaPlayer.positionChanged.connect(self.positionChanged)
        self.colorMediaPlayer.durationChanged.connect(self.durationChanged)
        self.colorMediaPlayer.error.connect(self.handleError)

        self.depthMediaPlayer.setVideoOutput(self.depthVideoWidget)
        self.depthMediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.depthMediaPlayer.positionChanged.connect(self.positionChanged)
        self.depthMediaPlayer.durationChanged.connect(self.durationChanged)
        self.depthMediaPlayer.error.connect(self.handleError)
Beispiel #48
0
    def initUI(self):
        '''
		第一個按鈕裡面的東西
		'''
        addAction = QAction(QIcon('./icon/add.png'), '新增商品', self)
        addAction.setShortcut('Alt+F1')
        addAction.setStatusTip('從內部資料庫新增商品')
        self.addwindow = addWindow()
        addAction.triggered.connect(self.addwindow.show)

        setAction = QAction(QIcon('./icon/set.png'), '設定商品', self)
        setAction.setShortcut('Alt+F2')
        self.setwindow = setWindow()
        setAction.triggered.connect(self.setwindow.show)
        setAction.setStatusTip('設定目前商品的細項')

        exitAction = QAction(QIcon('./icon/exit.png'), '離開', self)
        exitAction.setShortcut('Alt+F4')
        exitAction.triggered.connect(QCoreApplication.instance().quit)
        exitAction.setStatusTip('離開程式')
        '''
		第二個按鈕裡面的東西
		'''
        writeAction = QAction(QIcon('./icon/write.png'), '編寫', self)
        writeAction.setShortcut('Alt+W')
        self.writewindow = writeWindow()
        writeAction.triggered.connect(self.writewindow.show)
        writeAction.setStatusTip('手動編寫交易策略')

        checkAction = QAction(QIcon('./icon/check.png'), '查看', self)
        checkAction.setShortcut('Alt+C')
        self.checkwindow = checkWindow()
        checkAction.triggered.connect(self.checkwindow.show)
        checkAction.setStatusTip('查看內建的交易策略')
        '''
		第三個按鈕裡面的東西
		'''
        reportAction = QAction(QIcon('./icon/report.png'), '策略績效報告', self)
        reportAction.setShortcut('Alt+R')
        reportAction.setStatusTip('檢視此次交易策略之績效報告')
        self.reportwindow = reportWindow()
        reportAction.triggered.connect(self.reportwindow.show)
        '''
		第四個按鈕裡面的東西
		'''
        exchangeAction = QAction(QIcon('./icon/exchange.png'), '選擇證券交易所', self)
        self.exchangewindow = exchangeWindow()
        exchangeAction.setShortcut('Alt+X')
        exchangeAction.triggered.connect(self.exchangewindow.show)
        exchangeAction.setStatusTip('選擇欲交易之證券交易所')

        orderAction = QAction(QIcon('./icon/order.png'), '下單', self)
        self.tradewindow = tradeWindow()
        orderAction.setShortcut('Alt+O')
        orderAction.triggered.connect(self.tradewindow.show)
        orderAction.setStatusTip('與證券交易所進行交易')
        '''
		第五個按鈕
		'''
        loginAction = QAction(QIcon('./icon/login.png'), '登入', self)
        self.loginwindow = loginWindow()
        loginAction.setShortcut('Alt+L')
        loginAction.triggered.connect(self.loginwindow.show)
        loginAction.setStatusTip('登入')

        self.statusBar()
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('商品')
        fileMenu2 = menubar.addMenu('交易策略')
        fileMenu3 = menubar.addMenu('檢視績效報告')
        fileMenu4 = menubar.addMenu('下單接口')
        fileMenu5 = menubar.addMenu('進階')
        fileMenu.addAction(addAction)
        fileMenu.addAction(setAction)
        fileMenu.addAction(exitAction)
        fileMenu2.addAction(writeAction)
        fileMenu2.addAction(checkAction)
        fileMenu3.addAction(reportAction)
        fileMenu4.addAction(exchangeAction)
        fileMenu4.addAction(orderAction)
        fileMenu5.addAction(loginAction)
        self.setWindowTitle('iTrader v0723')
        self.show()
Beispiel #49
0
def recentMenu(qact: QObject):
    files = recent.get().getFiles()
    return [QAction(f, qact) for f in files]
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        cwidget = QWidget()
        self.setCentralWidget(cwidget)

        self.createquestion()
        self.createimage()
        self.createresult()

        self.subutton = QPushButton("submit", self)
        self.subutton.clicked.connect(self.on_submit)
        self.subutton.hide()

        wLayout = QVBoxLayout()
        wLayout.addWidget(self.questiongroup)
        wLayout.addWidget(self.imagegroup)
        wLayout.addWidget(self.subutton)
        wLayout.addWidget(self.resultgroup)
        wLayout.setAlignment(Qt.AlignTop)

        cwidget.setLayout(wLayout)

        #Menu bar
        mainmenu = self.menuBar()
        option = mainmenu.addMenu("Options")
        hhelp = mainmenu.addMenu("Help")

        resetButton = QAction(QIcon("restart.png"), "Reset", self)
        resetButton.setShortcut("Ctrl+R")
        resetButton.setStatusTip("Reset image and question")
        resetButton.triggered.connect(self.reset)
        option.addAction(resetButton)

        exitButton = QAction(QIcon('exit.png'), 'Exit', self)
        exitButton.setShortcut('Ctrl+Q')
        exitButton.setStatusTip('Exit application')
        exitButton.triggered.connect(self.close)
        option.addAction(exitButton)

        helpButton = QAction(QIcon('help.png'), 'Help', self)
        helpButton.setShortcut('Ctrl+H')
        helpButton.setStatusTip('Help to run application')
        helpButton.triggered.connect(self.on_clickhelp)
        hhelp.addAction(helpButton)

        aboutButton = QAction(QIcon('about.png'), 'About', self)
        aboutButton.setShortcut('Ctrl+I')
        aboutButton.setStatusTip('About the application')
        aboutButton.triggered.connect(self.on_clickabout)
        hhelp.addAction(aboutButton)

        # Status bar
        self.statusBar().showMessage("Hello and Welcome to this Application")

        self.show()
Beispiel #51
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.curFile = ''

        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)

        self.createActions()
        self.createMenus()
        self.createToolBars()
        self.createStatusBar()

        self.readSettings()

        self.textEdit.document().contentsChanged.connect(
            self.documentWasModified)

        self.setCurrentFile('')

    def closeEvent(self, event):
        if self.maybeSave():
            self.writeSettings()
            event.accept()
        else:
            event.ignore()

    def newFile(self):
        if self.maybeSave():
            self.textEdit.clear()
            self.setCurrentFile('')

    def open(self):
        if self.maybeSave():
            fileName, _ = QFileDialog.getOpenFileName(self)
            if fileName:
                self.loadFile(fileName)

    def save(self):
        if self.curFile:
            return self.saveFile(self.curFile)

        return self.saveAs()

    def saveAs(self):
        fileName, _ = QFileDialog.getSaveFileName(self)
        if fileName:
            return self.saveFile(fileName)

        return False

    def about(self):
        QMessageBox.about(
            self, "About Application",
            "The <b>Application</b> example demonstrates how to write "
            "modern GUI applications using Qt, with a menu bar, "
            "toolbars, and a status bar.")

    def documentWasModified(self):
        self.setWindowModified(self.textEdit.document().isModified())

    def createActions(self):
        root = QFileInfo(__file__).absolutePath()

        self.newAct = QAction(QIcon(root + '/images/new.png'),
                              "&New",
                              self,
                              shortcut=QKeySequence.New,
                              statusTip="Create a new file",
                              triggered=self.newFile)

        self.openAct = QAction(QIcon(root + '/images/open.png'),
                               "&Open...",
                               self,
                               shortcut=QKeySequence.Open,
                               statusTip="Open an existing file",
                               triggered=self.open)

        self.saveAct = QAction(QIcon(root + '/images/save.png'),
                               "&Save",
                               self,
                               shortcut=QKeySequence.Save,
                               statusTip="Save the document to disk",
                               triggered=self.save)

        self.saveAsAct = QAction(
            "Save &As...",
            self,
            shortcut=QKeySequence.SaveAs,
            statusTip="Save the document under a new name",
            triggered=self.saveAs)

        self.exitAct = QAction("E&xit",
                               self,
                               shortcut="Ctrl+Q",
                               statusTip="Exit the application",
                               triggered=self.close)

        self.cutAct = QAction(
            QIcon(root + '/images/cut.png'),
            "Cu&t",
            self,
            shortcut=QKeySequence.Cut,
            statusTip="Cut the current selection's contents to the clipboard",
            triggered=self.textEdit.cut)

        self.copyAct = QAction(
            QIcon(root + '/images/copy.png'),
            "&Copy",
            self,
            shortcut=QKeySequence.Copy,
            statusTip="Copy the current selection's contents to the clipboard",
            triggered=self.textEdit.copy)

        self.pasteAct = QAction(
            QIcon(root + '/images/paste.png'),
            "&Paste",
            self,
            shortcut=QKeySequence.Paste,
            statusTip=
            "Paste the clipboard's contents into the current selection",
            triggered=self.textEdit.paste)

        self.aboutAct = QAction("&About",
                                self,
                                statusTip="Show the application's About box",
                                triggered=self.about)

        self.aboutQtAct = QAction("About &Qt",
                                  self,
                                  statusTip="Show the Qt library's About box",
                                  triggered=QApplication.instance().aboutQt)

        self.cutAct.setEnabled(False)
        self.copyAct.setEnabled(False)
        self.textEdit.copyAvailable.connect(self.cutAct.setEnabled)
        self.textEdit.copyAvailable.connect(self.copyAct.setEnabled)

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

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

        self.menuBar().addSeparator()

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

    def createToolBars(self):
        self.fileToolBar = self.addToolBar("File")
        self.fileToolBar.addAction(self.newAct)
        self.fileToolBar.addAction(self.openAct)
        self.fileToolBar.addAction(self.saveAct)

        self.editToolBar = self.addToolBar("Edit")
        self.editToolBar.addAction(self.cutAct)
        self.editToolBar.addAction(self.copyAct)
        self.editToolBar.addAction(self.pasteAct)

    def createStatusBar(self):
        self.statusBar().showMessage("Ready")

    def readSettings(self):
        settings = QSettings("Trolltech", "Application Example")
        pos = settings.value("pos", QPoint(200, 200))
        size = settings.value("size", QSize(400, 400))
        self.resize(size)
        self.move(pos)

    def writeSettings(self):
        settings = QSettings("Trolltech", "Application Example")
        settings.setValue("pos", self.pos())
        settings.setValue("size", self.size())

    def maybeSave(self):
        if self.textEdit.document().isModified():
            ret = QMessageBox.warning(
                self, "Application",
                "The document has been modified.\nDo you want to save "
                "your changes?",
                QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

            if ret == QMessageBox.Save:
                return self.save()

            if ret == QMessageBox.Cancel:
                return False

        return True

    def loadFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly | QFile.Text):
            QMessageBox.warning(
                self, "Application",
                "Cannot read file %s:\n%s." % (fileName, file.errorString()))
            return

        inf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.textEdit.setPlainText(inf.readAll())
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        self.statusBar().showMessage("File loaded", 2000)

    def saveFile(self, fileName):
        file = QFile(fileName)
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, "Application",
                "Cannot write file %s:\n%s." % (fileName, file.errorString()))
            return False

        outf = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        outf << self.textEdit.toPlainText()
        QApplication.restoreOverrideCursor()

        self.setCurrentFile(fileName)
        self.statusBar().showMessage("File saved", 2000)
        return True

    def setCurrentFile(self, fileName):
        self.curFile = fileName
        self.textEdit.document().setModified(False)
        self.setWindowModified(False)

        if self.curFile:
            shownName = self.strippedName(self.curFile)
        else:
            shownName = 'untitled.txt'

        self.setWindowTitle("%s[*] - Application" % shownName)

    def strippedName(self, fullFileName):
        return QFileInfo(fullFileName).fileName()
Beispiel #52
0
    def addLoadDataActions(self):
        loadDataFile = QAction(QIcon.fromTheme('open'), 'Load data.', self)
        loadDataFile.setShortcut('Ctrl+D')
        loadDataFile.setStatusTip(
            'Load experimental (.txt) / simulation (.param) data.')
        loadDataFile.triggered.connect(self.loadDisplayData)

        clearDataFileAct = QAction(QIcon.fromTheme('close'), 'Clear data.',
                                   self)
        clearDataFileAct.setShortcut('Ctrl+C')
        clearDataFileAct.setStatusTip('Clear data.')
        clearDataFileAct.triggered.connect(self.clearDataFile)

        self.fileMenu.addAction(loadDataFile)
        self.fileMenu.addAction(clearDataFileAct)
Beispiel #53
0
    def __init__(self, sequence: GifSequence,
                 meme_template: MemeAnimationTemplate, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.setWindowTitle(f"Animator")
        self.original_sequence = sequence
        self.meme_template = meme_template
        self.selected_text_template = meme_template.templates_list[0]
        self.render_options = {
            key: key
            for key in self.meme_template.templates_dict.keys()
        }
        self.current_frame_index = 0

        # self.keyframes_indicator = KeyframesIndicator(self)
        self.frame_properties_panel = FramePropertiesPanel(parent=self)
        self.frame_properties_panel.on_selected_frame_change()

        self.text_template_properties_panel = TextTemplatePropertiesPanel(
            parent=self)
        self.selected_text_template_changed.connect(
            lambda _: self.text_template_properties_panel.refresh())
        # self.frame_properties_panel.toggleKeyframeButton.clicked.connect(self.keyframes_indicator.refresh)

        self.frames_slider = QSlider(Qt.Horizontal, self)
        self.frames_slider.setMinimum(0)
        self.frames_slider.setMaximum(len(self.original_sequence) - 1)
        self.frames_slider.setTickPosition(QSlider.TicksBelow)
        self.frames_slider.valueChanged[int].connect(self.on_change_frame)
        self.frames_slider.valueChanged[int].connect(
            self.frame_properties_panel.on_selected_frame_change)

        self.frames_viewer = FramesViewer(sequence=self.original_sequence,
                                          parent=self)
        self.frames_slider.valueChanged[int].connect(
            self.frames_viewer.handle_frame_update)
        self.frames_viewer.setCursor(QtGui.QCursor(Qt.CrossCursor))

        self.text_template_properties_panel.text_template_properties_changed.connect(
            self.frames_viewer.update)

        left_side_widget = QWidget()
        left_layout = QVBoxLayout()
        self.add_text_template_button = QPushButton('Add New Text Template',
                                                    self)
        self.add_text_template_button.clicked.connect(
            self.on_click_add_text_template)

        self.delete_current_text_template_button = QPushButton(
            'Delete Current Text Template', self)
        self.delete_current_text_template_button.clicked.connect(
            self.on_click_delete_current_text_template)

        self.reset_button = QPushButton('Reset', self)
        self.reset_button.clicked.connect(self.on_click_reset)
        self.reset_button.clicked.connect(
            lambda _: self.frame_properties_panel.on_selected_frame_change())
        self.reset_button.clicked.connect(self.frames_viewer.update)

        loadAction = QAction("&Load animation", self)
        loadAction.setShortcut("Ctrl+O")
        loadAction.setStatusTip(
            'Load animation and existing template data if possible')
        loadAction.triggered.connect(self.on_click_load)

        saveAction = QAction("&Save template as", self)
        saveAction.setShortcut("Ctrl+S")
        saveAction.setStatusTip('Save animation data to a JSON file')
        saveAction.triggered.connect(self.on_click_save)

        resetAllAction = QAction("&Reset all animation data", self)
        resetAllAction.setShortcut("Ctrl+R")
        resetAllAction.setStatusTip(
            'Reset animation data in all text templates')
        resetAllAction.triggered.connect(self.on_click_reset_all)

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(saveAction)
        fileMenu.addAction(loadAction)
        fileMenu = mainMenu.addMenu('&Animation')
        fileMenu.addAction(resetAllAction)

        self.template_selection_panel = TemplateSelectionPanel(self)
        self.selected_text_template_changed.connect(
            lambda _: self.frame_properties_panel.on_selected_frame_change())
        self.selected_text_template_changed.connect(
            lambda _: self.template_selection_panel.refresh_selector())
        self.selected_text_template_changed.connect(
            lambda _: self.frames_viewer.update())

        left_layout.addWidget(self.frames_viewer)
        left_layout.addWidget(self.frames_slider)
        left_layout.addWidget(self.template_selection_panel)
        left_layout.addWidget(self.add_text_template_button)
        left_layout.addWidget(self.delete_current_text_template_button)
        left_layout.addWidget(self.reset_button)
        left_side_widget.setLayout(left_layout)

        right_side_widget = QWidget()
        right_layout = QVBoxLayout()
        right_layout.addWidget(self.frame_properties_panel)
        right_layout.addWidget(self.text_template_properties_panel)
        right_side_widget.setLayout(right_layout)

        main_widget = QWidget()
        main_layout = QHBoxLayout()
        main_layout.addWidget(left_side_widget)
        main_layout.addWidget(right_side_widget)
        main_widget.setLayout(main_layout)

        self.setCentralWidget(main_widget)
Beispiel #54
0
    def __init__(self,
                 *,
                 parent: 'ElectrumWindow',
                 desc,
                 prompt_if_unsaved,
                 finalized: bool,
                 external_keypairs=None):
        '''Transactions in the wallet will show their description.
        Pass desc to give a description for txs not yet in the wallet.
        '''
        # We want to be a top-level window
        QDialog.__init__(self, parent=None)
        self.tx = None  # type: Optional[Transaction]
        self.external_keypairs = external_keypairs
        self.finalized = finalized
        self.main_window = parent
        self.config = parent.config
        self.wallet = parent.wallet
        self.prompt_if_unsaved = prompt_if_unsaved
        self.saved = False
        self.desc = desc
        self.setMinimumWidth(1200)
        self.set_title()

        self.psbt_only_widgets = []  # type: List[QWidget]

        vbox = QVBoxLayout()
        self.setLayout(vbox)

        self.txid_lb = QLabel(_('Transaction ID:'))
        vbox.addWidget(self.txid_lb)
        self.tx_hash_e = ButtonsLineEdit()
        qr_show = lambda: parent.show_qrcode(
            str(self.tx_hash_e.text()), 'Transaction ID', parent=self)
        qr_icon = "qrcode.png"
        self.tx_hash_e.addButton(qr_icon, qr_show, _("Show as QR code"))
        self.tx_hash_e.setReadOnly(True)
        vbox.addWidget(self.tx_hash_e)

        self.add_tx_stats(vbox)

        vbox.addSpacing(10)

        self.inputs_header = QLabel()
        vbox.addWidget(self.inputs_header)
        self.inputs_textedit = QTextEditWithDefaultSize()
        vbox.addWidget(self.inputs_textedit)

        self.txo_color_recv = TxOutputColoring(
            legend=_("Receiving Address"),
            color=ColorScheme.GREEN,
            tooltip=_("Wallet receive address"))
        self.txo_color_change = TxOutputColoring(
            legend=_("Change Address"),
            color=ColorScheme.YELLOW,
            tooltip=_("Wallet change address"))

        outheader_hbox = QHBoxLayout()
        outheader_hbox.setContentsMargins(0, 0, 0, 0)
        vbox.addLayout(outheader_hbox)
        self.outputs_header = QLabel()
        outheader_hbox.addWidget(self.outputs_header)
        outheader_hbox.addStretch(2)
        outheader_hbox.addWidget(self.txo_color_recv.legend_label)
        outheader_hbox.addWidget(self.txo_color_change.legend_label)

        self.outputs_textedit = QTextEditWithDefaultSize()
        vbox.addWidget(self.outputs_textedit)

        self.sign_button = b = QPushButton(_("Sign"))
        b.clicked.connect(self.sign)

        self.broadcast_button = b = QPushButton(_("Broadcast"))
        b.clicked.connect(self.do_broadcast)

        self.save_button = b = QPushButton(_("Save"))
        b.clicked.connect(self.save)

        self.cancel_button = b = QPushButton(_("Close"))
        b.clicked.connect(self.close)
        b.setDefault(True)

        self.export_actions_menu = export_actions_menu = QMenu()
        self.add_export_actions_to_menu(export_actions_menu)
        export_actions_menu.addSeparator()
        export_submenu = export_actions_menu.addMenu(
            _("For CoinJoin; strip privates"))
        self.add_export_actions_to_menu(export_submenu,
                                        gettx=self._gettx_for_coinjoin)
        self.psbt_only_widgets.append(export_submenu)
        export_submenu = export_actions_menu.addMenu(
            _("For hardware device; include xpubs"))
        self.add_export_actions_to_menu(export_submenu,
                                        gettx=self._gettx_for_hardware_device)
        self.psbt_only_widgets.append(export_submenu)

        self.export_actions_button = QToolButton()
        self.export_actions_button.setObjectName("blue_toolbutton")
        self.export_actions_button.setText(_("Export"))
        self.export_actions_button.setMenu(export_actions_menu)
        self.export_actions_button.setPopupMode(QToolButton.InstantPopup)

        self.finalize_button = QPushButton(_('Finalize'))
        self.finalize_button.clicked.connect(self.on_finalize)

        partial_tx_actions_menu = QMenu()
        ptx_merge_sigs_action = QAction(_("Merge signatures from"), self)
        ptx_merge_sigs_action.triggered.connect(self.merge_sigs)
        partial_tx_actions_menu.addAction(ptx_merge_sigs_action)
        self.partial_tx_actions_button = QToolButton()
        self.partial_tx_actions_button.setObjectName("blue_toolbutton")
        self.partial_tx_actions_button.setText(_("Combine"))
        self.partial_tx_actions_button.setMenu(partial_tx_actions_menu)
        self.partial_tx_actions_button.setPopupMode(QToolButton.InstantPopup)
        self.psbt_only_widgets.append(self.partial_tx_actions_button)

        # Action buttons
        self.buttons = [
            self.partial_tx_actions_button, self.sign_button,
            self.broadcast_button, self.cancel_button
        ]
        # Transaction sharing buttons
        self.sharing_buttons = [
            self.finalize_button, self.export_actions_button, self.save_button
        ]
        run_hook('transaction_dialog', self)
        self.hbox = hbox = QHBoxLayout()
        hbox.addLayout(Buttons(*self.sharing_buttons))
        hbox.addStretch(1)
        hbox.addLayout(Buttons(*self.buttons))
        vbox.addLayout(hbox)
        self.set_buttons_visibility()

        dialogs.append(self)
Beispiel #55
0
class Main(QMainWindow):
    def __init__(self, app, palette, editor, parent=None):
        super().__init__(parent)

        self.editor = editor
        self.onStart(choiceIndex)
        self.status = QStatusBar(self)
        # Initializing the main widget where text is displayed
        self.tab = Tabs(self.openFile, app, palette, self)
        self.tabsOpen = []
        self.pic_opened = False
        self.dialog = MessageBox(self)

        self.setWindowIcon(QIcon('resources/Python-logo-notext.svg_.png')
                           )  # Setting the window icon

        self.setWindowTitle('PyPad')  # Setting the window title

        self.status_font = QFont(editor["statusBarFont"],
                                 editor["statusBarFontSize"])

        self.os = platform.system()

        self.tab.tabs.currentChanged.connect(self.fileNameChange)
        self.search = DocumentSearch()
        self.openterm()
        self.openterminal()
        # self.split2Tabs()
        self.new()
        self.newProject()
        self.findDocument()
        self.openProjectF()
        self.open()
        self.save()
        self.saveAs()
        self.exit()

        self.thread = UpdateThread()
        self.thread.start()

        self.thread.textSignal.connect(self.check_updates)

        self.dir_opened = False
        self._dir = None

        self.update_progress = QProgressBar()
        self.update_progress.setMaximumWidth(225)

        self.update_progress.setStyleSheet(self.update_progress.styleSheet())

        self.setCentralWidget(self.tab)

        self.files = None  # Tracking the current file that is open

        self.cFileOpened = False

        self.update_process = QProcess()

        self.initUI()  # Main UI

    def check_updates(self, text):

        self.update_label = QLabel()
        self.update_label.setFont(
            QFont(self.editor["generalFont"], self.editor["generalFontSize"]))
        self.update_label.setFont(self.status_font)
        self.update_label.setText(text)
        self.status.addWidget(self.update_label)

        if text != "An update is available, would you like to update?":
            pass
        else:
            self.button = QPushButton("Update")
            self.button.setFont(
                QFont(self.editor["generalFont"],
                      self.editor["generalFontSize"]))
            self.status.addWidget(self.button)
            self.button.clicked.connect(self.update_pypad)

    def update_pypad(self):
        self.update_label.setText("Updating...")
        self.status.removeWidget(self.button)
        self.status.addWidget(self.update_progress)
        """
        So "updating" means I should first have an executeable or something of that sorts
        """

        for i in range(101):
            self.update_progress.setValue(i)
            QTest.qWait(random.randint(50, 75))
        # make_decision(True)

    def fileNameChange(self):

        try:
            currentFileName = self.tab.tabs.currentWidget().baseName
            self.setWindowTitle("PyPad ~ " + str(currentFileName))

        except AttributeError:
            self.setWindowTitle("PyPad ~ ")

    def onStart(self, index):

        try:
            editor = configs[index]['editor']
            if editor["windowStaysOnTop"] is True:
                self.setWindowFlags(Qt.WindowStaysOnTopHint)

            else:
                pass

        except Exception as err:
            pass  # log exception

        self.font = QFont()
        self.font.setFamily(self.editor["editorFont"])

        self.font.setPointSize(self.editor["editorFontSize"])
        self.tabSize = self.editor["TabWidth"]

    def initUI(self):

        self.setStatusBar(self.status)  # Initializing the status bar

        self.font.setFixedPitch(True)
        menuFont = QFont()
        menuFont.setFamily(self.editor["menuFont"])
        menuFont.setPointSize(self.editor['menuFontSize'])
        menu = self.menuBar()
        menu.setFont(menuFont)
        # Creating the file menu

        fileMenu = menu.addMenu('File')

        # Adding options to the file menu
        # self.setStatusBar(self.status)
        fileMenu.addAction(self.newAct)
        fileMenu.addAction(self.newProjectAct)
        fileMenu.addAction(self.openAct)
        fileMenu.addAction(self.openProjectAct)
        fileMenu.addAction(self.saveAct)
        fileMenu.addAction(self.saveAsAct)
        fileMenu.addSeparator()
        fileMenu.addAction(self.exitAct)

        toolMenu = menu.addMenu('Tools')
        toolMenu.addAction(self.openTermAct)
        toolMenu.addAction(self.openTerminalAct)
        # toolMenu.addAction(self.split2TabsAct)

        searchDoc = menu.addMenu('Find document')

        searchDoc.addAction(self.findDocumentAct)

        self.showMaximized()

    def open(self):
        self.openAct = QAction('Open...', self)
        self.openAct.setShortcut('Ctrl+O')

        self.openAct.setStatusTip('Open a file')
        self.openAct.triggered.connect(self.openFileFromMenu)

    def closeEvent(self, QCloseEvent):

        os._exit(42)  # This makes sure every thread gets killed

    def new(self):
        self.newAct = QAction('New')
        self.newAct.setShortcut('Ctrl+N')

        self.newAct.setStatusTip('Create a new file')
        self.newAct.triggered.connect(self.newFile)

    def newProject(self):
        self.newProjectAct = QAction('New project')
        self.newProjectAct.setShortcut('Ctrl+Shift+N')

        self.newProjectAct.setStatusTip('Create a new project')
        self.newProjectAct.triggered.connect(self.newProjectFolder)

    def openProjectF(self):
        self.openProjectAct = QAction('Open project')
        self.openProjectAct.setShortcut('Ctrl+Shift+O')

        self.openProjectAct.setStatusTip('Open a project')
        self.openProjectAct.triggered.connect(self.openProject)

    def split2Tabs(self):
        self.split2TabsAct = QAction('Split the first 2 tabs')
        self.split2TabsAct.setShortcut('Ctrl+Alt+S')

        self.split2TabsAct.setStatusTip("Splits the first 2 tabs into one tab")
        self.split2TabsAct.triggered.connect(self.tab.split)

    def switchTabs(self):
        if self.tab.tabs.count() - 1 == self.tab.tabs.currentIndex():
            self.tab.tabs.setCurrentIndex(0)
        else:
            self.tab.tabs.setCurrentIndex(self.tab.tabs.currentIndex() + 1)

    def save(self):
        self.saveAct = QAction('Save')
        self.saveAct.setShortcut('Ctrl+S')

        self.saveAct.setStatusTip('Save a file')
        self.saveAct.triggered.connect(self.saveFile)

    def openterm(self):
        self.openTermAct = QAction('Run', self)
        self.openTermAct.setShortcut('Shift+F10')

        self.openTermAct.setStatusTip('Run your code')
        self.openTermAct.triggered.connect(self.execute_file)

    def openterminal(self):
        self.openTerminalAct = QAction("Terminal", self)
        self.openTerminalAct.setShortcut("Ctrl+T")

        self.openTerminalAct.setStatusTip("Open a terminal")
        self.openTerminalAct.triggered.connect(self.realterminal)

    def saveAs(self):
        self.saveAsAct = QAction('Save As...')
        self.saveAsAct.setShortcut('Ctrl+Shift+S')

        self.saveAsAct.setStatusTip('Save a file as')
        self.saveAsAct.triggered.connect(self.saveFileAs)

    def findDocument(self):
        self.findDocumentAct = QAction('Find document')
        self.findDocumentAct.setShortcut('Ctrl+Shift+F')

        self.findDocumentAct.setStatusTip('Find a document')
        self.findDocumentAct.triggered.connect(self.temp)

    def temp(self):
        pass

    def findDocumentFunc(self):

        self.search.run()

    def exit(self):
        self.exitAct = QAction('Quit', self)
        self.exitAct.setShortcut('Ctrl+Q')

        self.exitAct.setStatusTip('Exit application')
        self.exitAct.triggered.connect(qApp.quit)

    def openFileFromMenu(self):
        options = QFileDialog.Options()

        filenames, _ = QFileDialog.getOpenFileNames(
            self,
            'Open a file',
            '',
            'All Files (*);;Python Files (*.py);;Text Files (*.txt)',
            options=options)

        if filenames:  # If file is selected, we can open it
            filename = filenames[0]
            if filename[-3:] in ['gif', 'png', 'jpg', 'bmp'
                                 ] or filename[-4:] in ['jpeg']:
                self.pic_opened = True
            self.openFile(filename)

    def openBrowser(self, url, word):
        widget = Browser(url)
        index = self.tab.tabs.addTab(widget, "Info about: " + str(word))
        self.tab.tabs.setCurrentIndex(index)

    def openFile(self, filename):

        try:
            for index, tabName in enumerate(self.tab.tabCounter):
                with open(filename, 'r+') as file_o:
                    if filename[-3:] in ['gif', 'png', 'jpg', 'bmp'
                                         ] or filename[-4:] in ['jpeg']:
                        self.pic_opened = True
                    else:
                        self.pic_opened = False
                    try:
                        text = file_o.read()

                    except UnicodeDecodeError as E:
                        text = str(E)

                    basename = os.path.basename(filename)
                    if not self.pic_opened:
                        tab = Content(text, filename, basename, self)
                        tab.saved = True
                        tab.modified = False
                    else:
                        tab = Image(filename, basename)
                if tabName == tab.baseName:
                    self.tab.tabs.removeTab(index)

                    self.tab.tabCounter.remove(tab.baseName)
            try:
                with open(filename, 'r+') as file_o:
                    try:
                        if self.pic_opened is not True:
                            text = file_o.read()
                        else:
                            text = None
                    except (FileNotFoundError, UnicodeDecodeError,
                            AttributeError) as E:
                        text = str(E)

            except FileNotFoundError:
                with open(filename, 'w+') as newFileCreated:
                    text = newFileCreated.read()

            basename = os.path.basename(filename)
            if self.pic_opened is True:
                tab = Image(filename, basename)

            else:
                tab = Content(text, filename, basename,
                              self)  # Creating a tab object *IMPORTANT*
                tab.saved = True
                tab.modified = False
            self.tab.tabCounter.append(tab.baseName)
            dirPath = os.path.dirname(filename)
            self.files = filename

            self.tabsOpen.append(self.files)

            index = self.tab.tabs.addTab(
                tab, tab.baseName
            )  # This is the index which we will use to set the current
            self.tab.tabs.setTabToolTip(index, str(tab.fileName))
            if not self.dir_opened:  # If a project isnt opened then we open a directory everytime we open a file
                self.tab.directory.openDirectory(dirPath)

                self.tab.showDirectory()
            else:
                pass

            self.tab.setLayout(self.tab.layout)  # Finally we set the layout
            update_previous_file(filename)
            self.tab.tabs.setCurrentIndex(
                index)  # Setting the index so we could find the current widget

            self.currentTab = self.tab.tabs.currentWidget()

            if self.pic_opened is not True:
                self.currentTab.editor.setFont(self.font)  # Setting the font
                self.currentTab.editor.setFocus(
                )  # Setting focus to the tab after we open it

            self.pic_opened = False
        except (IsADirectoryError, AttributeError, UnboundLocalError,
                PermissionError) as E:
            print(E, " on line 346 in the file main.py")

    def newFile(self):
        text = ""
        if self._dir:
            base_file_name = "Untitled_file_" + str(random.randint(
                1, 100)) + ".py"
            fileName = str(self._dir) + "/" + base_file_name
        else:
            base_file_name = "Untitled_file_" + str(random.randint(
                1, 100)) + ".py"
            current = os.getcwd()
            fileName = current + "/" + base_file_name

        self.pyFileOpened = True
        # Creates a new blank file
        file = Content(text, fileName, base_file_name, self)
        self.tab.splitterH.addWidget(
            self.tab.tabs
        )  # Adding tabs, now the directory tree will be on the left
        self.tab.tabCounter.append(file.fileName)
        self.tab.setLayout(self.tab.layout)  # Finally we set the layout
        index = self.tab.tabs.addTab(
            file, file.baseName
        )  # addTab method returns an index for the tab that was added
        self.tab.tabs.setTabToolTip(index, str(file.fileName))
        self.tab.tabs.setCurrentIndex(
            index)  # Setting focus to the new tab that we created
        widget = self.tab.tabs.currentWidget()

    def newProjectFolder(self):
        self.dialog = NewProject(self)
        self.dialog.show()

    def openProject(self):

        self._dir = QFileDialog.getExistingDirectory(None, 'Select a folder:',
                                                     '',
                                                     QFileDialog.ShowDirsOnly)

        self.tab.directory.openDirectory(self._dir)
        self.dir_opened = True
        self.tab.showDirectory()

    def openProjectWithPath(self, path):

        self.tab.directory.openDirectory(path)
        self.dir_opened = True
        self._dir = path
        self.tab.showDirectory()

    def saveFile(self):
        try:
            active_tab = self.tab.tabs.currentWidget()
            if self.tab.tabs.count():  # If a file is already opened
                with open(active_tab.fileName, 'w+') as saveFile:
                    saveFile.write(active_tab.editor.toPlainText())
                    active_tab.saved = True
                    self.tab.events.look_for_dead_code(
                        active_tab.editor.toPlainText())
                    active_tab.modified = False
                    saveFile.close()
                if active_tab.fileName.endswith(".py"):
                    active_tab.editor.updateAutoComplete(active_tab.fileName)
            else:
                options = QFileDialog.Options()
                name = QFileDialog.getSaveFileName(
                    self,
                    'Save File',
                    '',
                    'All Files (*);;Python Files (*.py);;Text Files (*.txt)',
                    options=options)
                fileName = name[0]

                with open(fileName, "w+") as saveFile:
                    active_tab.saved = True
                    active_tab.modified = False
                    self.tabsOpen.append(fileName)
                    saveFile.write(active_tab.editor.toPlainText())
                    self.tab.events.look_for_dead_code(
                        active_tab.editor.toPlainText())
                    saveFile.close()
                    if fileName.endswith(".py"):
                        active_tab.editor.updateAutoComplete(
                            active_tab.fileName)
            self.setWindowTitle("PyPad ~ " + str(active_tab.baseName) +
                                " [SAVED]")
            active_tab.tokenize_file()
        except Exception as E:
            print(E, " on line 403 in the file main.py")

    def choose_python(self):
        if self.os == "Windows":
            return "python"

        elif self.os == "Linux":
            return "python3"

        elif self.os == "Darwin":
            return "python3"

    def saveFileAs(self):
        try:
            active_tab = self.tab.tabs.currentWidget()
            if active_tab is not None:
                active_index = self.tab.tabs.currentIndex()

                options = QFileDialog.Options()
                name = QFileDialog.getSaveFileName(
                    self,
                    'Save File',
                    '',
                    'All Files (*);;Python Files (*.py);;Text Files (*.txt)',
                    options=options)
                fileName = name[0]
                with open(fileName, "w+") as saveFile:
                    active_tab.saved = True
                    active_tab.modified = False
                    self.tabsOpen.append(fileName)

                    try:
                        baseName = os.path.basename(fileName)
                    except AttributeError:
                        print("All tabs closed")
                    saveFile.write(active_tab.editor.toPlainText())
                    text = active_tab.editor.toPlainText()
                    newTab = Content(str(text), fileName, baseName, self)
                    newTab.ready = True
                    self.tab.tabs.removeTab(
                        active_index
                    )  # When user changes the tab name we make sure we delete the old one
                    index = self.tab.tabs.addTab(
                        newTab, newTab.baseName)  # And add the new one!
                    self.tab.tabs.setTabToolTip(index, str(newTab.fileName))

                    self.tab.tabs.setCurrentIndex(index)
                    newActiveTab = self.tab.tabs.currentWidget()

                    newActiveTab.editor.setFont(self.font)
                    newActiveTab.editor.setFocus()

                    saveFile.close()
                self.setWindowTitle("PyPad ~ " + str(active_tab.baseName) +
                                    " [SAVED]")

            else:
                print("No file opened")

        except FileNotFoundError:
            print("File dialog closed")

    def realterminal(self):
        """
        Checking if the file executing widget already exists in the splitter layout:

        If it does exist, then we're going to replace the widget with the terminal widget, if it doesn't exist then
        just add the terminal widget to the layout and expand the splitter.

        """

        if self.tab.splitterV.indexOf(self.tab.Console) == 1:
            self.tab.splitterV.replaceWidget(
                self.tab.splitterV.indexOf(self.tab.Console),
                self.tab.terminal)
            self.tab.splitterV.setSizes([400, 10])
        else:
            self.tab.showConsole()

    def open_documentation(self, data, word):
        """
        Opens documentation for a built in function
        """
        data = data.replace("|", "")
        index = self.tab.tabs.addTab(
            Content(data,
                    os.getcwd() + "/" + str(word) + ".doc",
                    str(word) + ".doc", self, True), str(word))
        self.tab.tabs.setCurrentIndex(index)

    def execute_file(self):
        """
        Checking if the terminal widget already exists in the splitter layout:

        If it does exist, then we're going to replace it, if it doesn't then we're just gonna add our file executer to
        the layout, expand the splitter and run the file.

        Then check if the file executer already exists, but is called again to run the file again

        """
        active_tab = self.tab.tabs.currentWidget()
        python_command = self.choose_python()
        if self.tab.splitterV.indexOf(self.tab.terminal) == 1:
            self.tab.splitterV.replaceWidget(
                self.tab.splitterV.indexOf(self.tab.terminal),
                self.tab.Console)
            self.tab.Console.run(
                "{} ".format(python_command) + active_tab.fileName,
                active_tab.fileName)
            self.tab.splitterV.setSizes([400, 10])

        elif self.tab.splitterV.indexOf(self.tab.Console) == 1:
            self.tab.Console.run(
                "{} ".format(python_command) + active_tab.fileName,
                active_tab.fileName)
            self.tab.splitterV.setSizes([400, 10])
        else:
            self.tab.showFileExecuter()
            self.tab.Console.run(
                "{} ".format(python_command) + active_tab.fileName,
                active_tab.fileName)
            self.tab.splitterV.setSizes([400, 10])
Beispiel #56
0
    def createActions(self):
        root = QFileInfo(__file__).absolutePath()

        self.newAct = QAction(QIcon(root + '/images/new.png'),
                              "&New",
                              self,
                              shortcut=QKeySequence.New,
                              statusTip="Create a new file",
                              triggered=self.newFile)

        self.openAct = QAction(QIcon(root + '/images/open.png'),
                               "&Open...",
                               self,
                               shortcut=QKeySequence.Open,
                               statusTip="Open an existing file",
                               triggered=self.open)

        self.saveAct = QAction(QIcon(root + '/images/save.png'),
                               "&Save",
                               self,
                               shortcut=QKeySequence.Save,
                               statusTip="Save the document to disk",
                               triggered=self.save)

        self.saveAsAct = QAction(
            "Save &As...",
            self,
            shortcut=QKeySequence.SaveAs,
            statusTip="Save the document under a new name",
            triggered=self.saveAs)

        self.exitAct = QAction("E&xit",
                               self,
                               shortcut="Ctrl+Q",
                               statusTip="Exit the application",
                               triggered=self.close)

        self.cutAct = QAction(
            QIcon(root + '/images/cut.png'),
            "Cu&t",
            self,
            shortcut=QKeySequence.Cut,
            statusTip="Cut the current selection's contents to the clipboard",
            triggered=self.textEdit.cut)

        self.copyAct = QAction(
            QIcon(root + '/images/copy.png'),
            "&Copy",
            self,
            shortcut=QKeySequence.Copy,
            statusTip="Copy the current selection's contents to the clipboard",
            triggered=self.textEdit.copy)

        self.pasteAct = QAction(
            QIcon(root + '/images/paste.png'),
            "&Paste",
            self,
            shortcut=QKeySequence.Paste,
            statusTip=
            "Paste the clipboard's contents into the current selection",
            triggered=self.textEdit.paste)

        self.aboutAct = QAction("&About",
                                self,
                                statusTip="Show the application's About box",
                                triggered=self.about)

        self.aboutQtAct = QAction("About &Qt",
                                  self,
                                  statusTip="Show the Qt library's About box",
                                  triggered=QApplication.instance().aboutQt)

        self.cutAct.setEnabled(False)
        self.copyAct.setEnabled(False)
        self.textEdit.copyAvailable.connect(self.cutAct.setEnabled)
        self.textEdit.copyAvailable.connect(self.copyAct.setEnabled)
Beispiel #57
0
    def findDocument(self):
        self.findDocumentAct = QAction('Find document')
        self.findDocumentAct.setShortcut('Ctrl+Shift+F')

        self.findDocumentAct.setStatusTip('Find a document')
        self.findDocumentAct.triggered.connect(self.temp)
Beispiel #58
0
    def __init__(self, dataset, rotateCrossSection=False):
        # TODO: make a better solution for rotateCrossSection, so
        # it does not have to be passed on to the widget
        QtWidgets.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        # Main Window
        self.setWindowTitle("QCoDeS Qt Ui")
        # self.setIcon(QIcon(getImageResourcePath('qcodes.png')))
        self.setWindowIcon(QIcon(getImageResourcePath('qcodes.png')))

        ## Actions

        # quit
        quit_action = QAction(QIcon(getImageResourcePath('quit.png')), 'Quit',
                              self)
        quit_action.setShortcut('Ctrl+q')
        quit_action.triggered.connect(self.onQuit)

        # file
        file_open_action = QAction(QIcon(getImageResourcePath('fileopen.png')),
                                   'Open', self)
        file_open_action.setShortcut('Ctrl+o')
        file_open_action.triggered.connect(self.onOpenFile)

        about_action = QAction(QIcon(getImageResourcePath('about.png')),
                               'About', self)
        about_action.triggered.connect(self.onAbout)

        ## Menus
        # File
        self.file_menu = QtWidgets.QMenu('&File', self)
        self.menuBar().addMenu(self.file_menu)
        self.file_menu.addAction(file_open_action)
        self.file_menu.addSeparator()
        self.file_menu.addAction(quit_action)

        # Tool
        tool_menu = QtWidgets.QMenu('&Tools', self)
        self.menuBar().addMenu(tool_menu)

        view_menu = QtWidgets.QMenu('&View', self)
        self.menuBar().addMenu(view_menu)

        # help
        self.help_menu = QtWidgets.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        self.help_menu.addAction(about_action)

        # toolbars
        tools_tool_bar = self.addToolBar('Tools')
        views_tool_bar = self.addToolBar('Views')
        toolbar2 = self.addToolBar('mplTools')

        # Tools
        tools = dict()

        def addTool(id, name, shortcut, tip, **kwargs):
            if 'icon' in kwargs.keys():
                tools[id] = QAction(kwargs['icon'], name, self, checkable=True)
            else:
                tools[id] = QAction(name, self)
            tools[id].setShortcut(shortcut)
            tools[id].setStatusTip(tip)
            tools_tool_bar.addAction(tools[id])
            tool_menu.addAction(tools[id])

        def addView(id, name, shortcut, tip, **kwargs):
            if 'icon' in kwargs.keys():
                tools[id] = QAction(kwargs['icon'], name, self)
            else:
                tools[id] = QAction(name, self)
            tools[id].setShortcut(shortcut)
            tools[id].setStatusTip(tip)
            views_tool_bar.addAction(tools[id])
            view_menu.addAction(tools[id])

        addView(
            'OrthoXSection',
            'Orthorgonal cross section',
            'Ctrl+r',
            'The orthorgonal cross section tool creates a profile of the data'
            + 'at a given point',
            icon=QIcon(getImageResourcePath('crosshair.png')))
        addView(
            'CustomXSection',
            'Custom cross section',
            'Ctrl+u',
            'The custom cross section tool creates a profile of the data between'
            + 'two given points',
            icon=QIcon(getImageResourcePath('customXSection.png')))
        addView(
            'sumXSection',
            'sum cross section',
            'Ctrl+u',
            'The sum cross section tool creates a profile of the data between'
            + 'by summing all datapoints',
            icon=getIconFromLetter('Σ', '#5f8cba'))
        addTool(
            'planeFit',
            'Plane fit',
            'Ctrl+f',
            'Substract any linear background by fitting a plane to the data' +
            'and substracting it',
            icon=QIcon(getImageResourcePath('planeFit.png')))
        addTool('selectionTool',
                'Select',
                'Ctrl+e',
                'Select region to appy modifications',
                icon=QIcon(getImageResourcePath('selectionTool.png')))
        addTool('restore',
                'restore',
                'Ctrl+r',
                'restore data',
                icon=QIcon(getImageResourcePath('restore.png')))
        addTool('SavePlotsPDF',
                'Save all plots as pdf',
                'Ctrl+s',
                '' + '',
                icon=QIcon(getImageResourcePath('savePdf.png')))
        addTool('SavePlotsPNG',
                'Save all plots as png',
                '',
                '' + '',
                icon=QIcon(getImageResourcePath('savePng.png')))
        # Widgets

        # Data array dock
        self.data_array_widget = DataArrayListWidget(self.dataArrayChanged)
        data_array_dock = QDockWidget("Data arrays", self)
        data_array_dock.setWidget(self.data_array_widget)
        data_array_dock.setFloating(False)

        # Main Widget
        self.main_widget = QtWidgets.QWidget(self)
        self.setCentralWidget(self.main_widget)
        self.addDockWidget(Qt.LeftDockWidgetArea, data_array_dock)

        l = QtWidgets.QVBoxLayout(self.main_widget)
        qt_toolbar = QWidget()
        qt_toolbar.setFixedSize(450, 40)
        # qt_toolbar.setBaseSize(400,40)
        qt_toolbar.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                 QtWidgets.QSizePolicy.Expanding)
        l.addWidget(qt_toolbar)

        self.cross_section_widget = CrossSectionWidget(
            self.dataArrayChanged,
            qt_toolbar,
            tools=tools,
            rotateCrossSection=rotateCrossSection)
        l.addWidget(cw)

        self.main_widget.setFocus()

        self.statusBar().showMessage("Starting", 2000)
        self.data_array_widget.loadDataSet(dataset)
Beispiel #59
0
    def saveAs(self):
        self.saveAsAct = QAction('Save As...')
        self.saveAsAct.setShortcut('Ctrl+Shift+S')

        self.saveAsAct.setStatusTip('Save a file as')
        self.saveAsAct.triggered.connect(self.saveFileAs)
Beispiel #60
0
    def exit(self):
        self.exitAct = QAction('Quit', self)
        self.exitAct.setShortcut('Ctrl+Q')

        self.exitAct.setStatusTip('Exit application')
        self.exitAct.triggered.connect(qApp.quit)