Exemplo n.º 1
0
    def set_images(self, images, scroll_area):
        row = 0
        col = 0
        grid_layout = QGridLayout()
        grid_layout.setHorizontalSpacing(1)
        grid_layout.setVerticalSpacing(1)
        self._actions = []
        for i in range(len(images)):
            qim = ImageQt(images[i])
            pixmap = QPixmap.fromImage(qim)
            ql = QLabel()
            ql.setPixmap(pixmap)
            ql.setScaledContents(True)
            ql.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            ql.setContextMenuPolicy(Qt.ActionsContextMenu)
            action = QAction('Export Tile #{} to BMP'.format(i), self)
            action.triggered.connect(
                (lambda idx: lambda: self.export_tile(images[idx]))(i))
            self._actions.append(action)
            ql.addAction(action)
            grid_layout.addWidget(ql, row, col)

            col += 1
            if col >= self._COL_WIDTH:
                row += 1
                col = 0

        client = QWidget()
        scroll_area.setWidget(client)
        client.setLayout(grid_layout)
Exemplo n.º 2
0
    def set_images(self, images, scroll_area, start_index=1, column_width=14):
        def update_dimensions(rows, columns, column_width):
            columns += 1
            if columns >= column_width > 0:
                rows += 1
                columns = 0

            return rows, columns

        rows, columns = 0, 0
        grid_layout = QGridLayout()
        grid_layout.setHorizontalSpacing(1)
        grid_layout.setVerticalSpacing(1)
        for i in range(len(images)):
            ql = QLabel()
            ql.setPixmap(QPixmap.fromImage(ImageQt(images[i])))
            ql.setScaledContents(True)
            ql.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            ql.setContextMenuPolicy(Qt.ActionsContextMenu)
            action = QAction('Export Tile {} to BMP'.format((i + start_index)), self)
            action.triggered.connect((lambda idx: lambda: self.export_tile(images[idx]))(i))
            self._actions.append(action)
            ql.addAction(action)
            grid_layout.addWidget(ql, rows, columns)

            rows, columns = update_dimensions(rows, columns, column_width)

        client = QWidget()
        scroll_area.setWidget(client)
        client.setLayout(grid_layout)
Exemplo n.º 3
0
class Windows(QMainWindow):
	def __init__(self , parent=None):
		super().__init__(parent)
		self.setWindowTitle("PyGUI Widget Design #1")


################################################################
#################### GUI DESIGINING BELOW ######################
################################################################

		self.setStyleSheet("""

QMenuBar {
    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                      stop:0 lightgray, stop:1 lightblue);
    spacing: 3px; 
}


QMenuBar::item:selected { 
    background: #a8a8a8;
}

QMenuBar::item:pressed {
    background: #888888;
}

QMenu {
    background-color: #b2eab1; 
    border: 1px solid black;
}

QMenu::item {
    background-color: transparent;
}

QMenu::item:selected { 
    background-color: #4b7c58;
}

QToolBar {
    background: lightblue;
    spacing: 10px; 
}
			""")
################################################################
#################### GUI DESIGINING ABOVE ######################
################################################################

		self.resize(800, 600)
		self.centralWidget = QLabel(text)

		self.label_a = QLabel(text, self)
		self.label_a.setFont(QFont("Arial" , 15))


		self.centralWidget = self.label_a
		self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

		self.setCentralWidget(self.centralWidget)
		self._createAction_()
		self._MenuBar_()
		self._createToolBars_()
		self._ContextMenu_()
		self._connectActions()
		self.createStatusBar()

################# FEATURE ADDING BELOW ##################

	def _MenuBar_(self):
		menuBar = self.menuBar()
        # File menu
		fileMenu = QMenu("&File", self)
		menuBar.addMenu(fileMenu)

		fileMenu.addAction(self.newAction)
		fileMenu.addAction(self.openAction)
		fileMenu.addAction(self.saveAction)
		fileMenu.addSeparator()
		fileMenu.addAction(self.exitAction)

        # Edit menu
		editMenu = menuBar.addMenu("&Edit")
		editMenu.addAction(self.copyAction)
		editMenu.addAction(self.pasteAction)
		editMenu.addAction(self.cutAction)
		editMenu.addSeparator()
		fileMenu2 = editMenu.addMenu("Find and Replace")
		fileMenu2.addAction("Find ? ")
		fileMenu2.addAction("Replace ? ") 
        # Help menu
		helpMenu = menuBar.addMenu(QIcon(":help-content.svg"), "&Help")
		helpMenu.addAction(self.helpContentAction)
		helpMenu.addAction(self.aboutAction)
		self.openRecentMenu = fileMenu.addMenu("Open Recent")


	def _createToolBars_(self):
		fileToolBar = self.addToolBar("File")
		fileToolBar.setMovable(False)
		editToolBar = QToolBar("Edit" , self)


		self.addToolBar(editToolBar)

		# File Toolbars
		fileToolBar.addAction(self.newAction)
		fileToolBar.addAction(self.openAction)
		fileToolBar.addAction(self.saveAction)
		# Editing Toolbars
		editToolBar.addAction(self.copyAction)
		editToolBar.addAction(self.pasteAction)
		editToolBar.addAction(self.cutAction)
		# WIDGETS!!!
		self.FONTspinBox = QSpinBox()
		self.FONTspinBox.setFocusPolicy(Qt.WheelFocus)
		editToolBar.addWidget(self.FONTspinBox)

	def _createAction_(self):
		self.newAction = QAction(self)
		self.newAction.setText("&New")
		self.openAction = QAction("&Open...", self)
		self.saveAction = QAction("&Save", self)
		self.exitAction = QAction("&Exit", self)
		self.copyAction = QAction("&Copy", self)
		self.pasteAction = QAction("&Paste", self)
		self.cutAction = QAction("&Cut", self)
		self.helpContentAction = QAction("&Help Content", self)
		self.aboutAction = QAction("&About", self)
		# Icons for File Action
		self.newAction.setIcon(QIcon(":file-new.svg"))
		self.openAction = QAction(QIcon(":file-open.svg"), "&Open", self)
		self.saveAction = QAction(QIcon(":file-save.svg"), "Save" , self)
		# Icons for Edit Actions
		self.copyAction = QAction(QIcon(":edit-copy.svg"), "&Copy", self)
		self.pasteAction = QAction(QIcon(":edit-paste.svg"), "Paste", self)
		self.cutAction = QAction(QIcon(":edit-cut.svg"), "Cut", self)
		# Shortcuts?
		self.newAction.setShortcut("Ctrl+N")
		self.openAction.setShortcut("Ctrl+O")
		self.saveAction.setShortcut("Ctrl+S")
		self.copyAction.setShortcut(QKeySequence.Copy)
		self.pasteAction.setShortcut(QKeySequence.Paste)
		self.cutAction.setShortcut(QKeySequence.Cut)

		# Adding status.....

		self.newAction.setStatusTip("Create a new file?")
		self.newAction.setToolTip("Create?")

		self.openAction.setStatusTip("Open a new file?")
		self.openAction.setToolTip("Open?")

		self.saveAction.setStatusTip("Save the file?")
		self.saveAction.setToolTip("Save?")

		self.copyAction.setStatusTip("Copy something?")
		self.copyAction.setToolTip("Copy?")

		self.pasteAction.setStatusTip("Paste something?")
		self.pasteAction.setToolTip("Paste?")

		self.cutAction.setStatusTip("Move something?")
		self.cutAction.setToolTip("Move?")

		self.helpContentAction.setStatusTip("Help Content....")
		self.aboutAction.setStatusTip("About File....")





	def _ContextMenu_(self):
		self.centralWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
		self.centralWidget.addAction(self.newAction)
		self.centralWidget.addAction(self.openAction)
		self.centralWidget.addAction(self.saveAction)
		self.centralWidget.addAction(self.copyAction)
		self.centralWidget.addAction(self.pasteAction)
		self.centralWidget.addAction(self.cutAction)

################################################################
################### SLOT CONNECTIONS BELOW #####################
################################################################

	def newFile(self):
		self.centralWidget.setText("""
			<i>User</i> Clicked <b>New File</b>, but where is the New File Feature?
			""")
	def openFile(self):
		self.centralWidget.setText("""
			<i>User</i> wants to <b>Open File</b>, but where is the in-app file browser?
			""")
	def saveFile(self):
		self.centralWidget.setText("How can you save when you didn't even write anything?")

	def copyContent(self):
		self.centralWidget.setText("<b>Copy chan</b> got GOT TRIGGERED?!")

	def pasteContent(self):
		self.centralWidget.setText("<b>Paste chan</b> got a Jackpot!!")

	def cutContent(self):
		self.centralWidget.setText("I'm sorry but we are not doing art here..")

	def helpContent(self):
		self.centralWidget.setText("<b>HELP chan</b> is out of Context?")

	def about(self):
		self.centralWidget.setText("READ THE <b>GITHUB</b>, LOL")


	def _connectActions(self):
		self.newAction.triggered.connect(self.newFile)
		self.openAction.triggered.connect(self.openFile)
		self.saveAction.triggered.connect(self.saveFile)
		self.exitAction.triggered.connect(self.close)
		# Connect Edit actions
		self.copyAction.triggered.connect(self.copyContent)
		self.pasteAction.triggered.connect(self.pasteContent)
		self.cutAction.triggered.connect(self.cutContent)	
		# Connect Help actions	
		self.helpContentAction.triggered.connect(self.helpContent)
		self.aboutAction.triggered.connect(self.about)
		# Connect Recent Open Files
		self.openRecentMenu.aboutToShow.connect(self.populate_the_recents)		

################################################################
################### SLOT CONNECTIONS ABOVE #####################
################################################################
	def populate_the_recents(self):
		self.openRecentMenu.clear()
		actions = []
		fileName = [f"File-{n}" for n in range(5)]
		for fileNames in fileName:
			action = QAction(fileNames, self)
			action.triggered.connect(partial(self.openRecentFile, fileNames))
			actions.append(action)
		self.openRecentMenu.addActions(actions)


	def openRecentFile(self, filename):
		self.centralWidget.setText(f"<b>{filename}</b> got opened?")

	def createStatusBar(self):
		self.statusBar = self.statusBar()
		self.setStatusBar(self.statusBar)
		Qlabel_text = QLabel("Open Sourced Project", self)
		self.statusBar.addPermanentWidget(Qlabel_text)
Exemplo n.º 4
0
class Window(QMainWindow):
    """Main Window."""
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        self.setWindowTitle("Python Menus & Toolbars")
        self.resize(400, 200)
        self.centralWidget = QLabel("Hello, World")
        self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.setCentralWidget(self.centralWidget)
        self._createActions()
        self._createMenuBar()
        self._createToolBars()
        # self._createContextMenu()
        self._connectActions()
        self._createStatusBar()

    def _createToolBars(self):
        # Using a title
        fileToolBar = self.addToolBar("File")
        fileToolBar.addAction(self.newAction)
        fileToolBar.addAction(self.openAction)
        fileToolBar.addAction(self.saveAction)
        # Using a QToolBar object
        editToolBar = QToolBar("Edit", self)
        self.addToolBar(editToolBar)
        editToolBar.addAction(self.copyAction)
        editToolBar.addAction(self.pasteAction)
        editToolBar.addAction(self.cutAction)
        # Using a QToolBar object and a toolbar area
        helpToolBar = QToolBar("Help", self)
        self.addToolBar(Qt.LeftToolBarArea, helpToolBar)

    def _createMenuBar(self):
        menuBar = self.menuBar()
        # Creating menus using a QMenu object
        fileMenu = QMenu("&File", self)
        menuBar.addMenu(fileMenu)
        fileMenu.addAction(self.newAction)
        fileMenu.addAction(self.openAction)
        # Adding an Open Recent submenu
        self.openRecentMenu = fileMenu.addMenu("Open Recent")
        fileMenu.addAction(self.saveAction)
        # Adding a separator
        fileMenu.addSeparator()
        fileMenu.addAction(self.exitAction)

        # Creating menus using a title
        editMenu = menuBar.addMenu("&Edit")
        editMenu.addAction(self.copyAction)
        editMenu.addAction(self.pasteAction)
        editMenu.addAction(self.cutAction)
        # Adding a separator
        fileMenu.addSeparator()
        findMenu = editMenu.addMenu("Find and Replace")
        findMenu.addAction("Find...")
        findMenu.addAction("Replace...")
        # Using an icon and a title
        helpMenu = menuBar.addMenu(QIcon(":help-content.svg"), "&Help")
        helpMenu.addAction(self.helpContentAction)
        helpMenu.addAction(self.aboutAction)

    def _createActions(self):
        # Creating action using the first constructor
        self.newAction = QAction(self)
        self.newAction.setText("&New")
        self.newAction.setIcon(QIcon(":file-new.svg"))

        # Creating actions using the second constructor
        self.openAction = QAction(QIcon(":file-open.svg"), "&Open...", self)
        self.saveAction = QAction(QIcon(":file-save.svg"), "&Save", self)
        self.exitAction = QAction("&Exit", self)
        self.copyAction = QAction(QIcon(":edit-copy.svg"), "&Copy", self)
        self.pasteAction = QAction(QIcon(":edit-paste.svg"), "&Paste", self)
        self.cutAction = QAction(QIcon(":edit-cut.svg"), "C&ut", self)
        self.helpContentAction = QAction("&Help Content", self)
        self.aboutAction = QAction("&About", self)
        # Using string-based key sequences
        self.newAction.setShortcut("Ctrl+N")
        self.openAction.setShortcut("Ctrl+O")
        self.saveAction.setShortcut("Ctrl+S")
        # Adding help tips
        newTip = "Create a new file"
        self.newAction.setStatusTip(newTip)
        self.newAction.setToolTip(newTip)
        # Using standard keys
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.cutAction.setShortcut(QKeySequence.Cut)

    def _createContextMenu(self):
        # Setting contextMenuPolicy
        self.centralWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
        # Populating the widget with actions
        self.centralWidget.addAction(self.newAction)
        self.centralWidget.addAction(self.openAction)
        self.centralWidget.addAction(self.saveAction)
        self.centralWidget.addAction(self.copyAction)
        self.centralWidget.addAction(self.pasteAction)
        self.centralWidget.addAction(self.cutAction)

    def getWordCount(self):
        # Logic for computing the word count goes here...
        return 42

    def _createStatusBar(self):
        self.statusbar = self.statusBar()
        # Adding a temporary message
        self.statusbar.showMessage("Ready", 3000)
        # Adding a permanent message
        self.wcLabel = QLabel(f"{self.getWordCount()} Words")
        self.statusbar.addPermanentWidget(self.wcLabel)

    def contextMenuEvent(self, event):
        # Creating a menu object with the central widget as parent
        menu = QMenu(self.centralWidget)
        # Populating the menu with actions
        menu.addAction(self.newAction)
        menu.addAction(self.openAction)
        menu.addAction(self.saveAction)
        # Creating a separator action
        separator = QAction(self)
        separator.setSeparator(True)
        # Adding the separator to the menu
        menu.addAction(separator)
        menu.addAction(self.copyAction)
        menu.addAction(self.pasteAction)
        menu.addAction(self.cutAction)
        # Launching the menu
        menu.exec(event.globalPos())

    def _connectActions(self):
        # Connect File actions
        self.newAction.triggered.connect(self.newFile)
        self.openAction.triggered.connect(self.openFile)
        self.saveAction.triggered.connect(self.saveFile)
        self.exitAction.triggered.connect(self.close)
        # Connect Edit actions
        self.copyAction.triggered.connect(self.copyContent)
        self.pasteAction.triggered.connect(self.pasteContent)
        self.cutAction.triggered.connect(self.cutContent)
        # Connect Help actions
        self.helpContentAction.triggered.connect(self.helpContent)
        self.aboutAction.triggered.connect(self.about)
        # Connect Open Recent to dynamically populate it
        self.openRecentMenu.aboutToShow.connect(self.populateOpenRecent)

    def openRecentFile(self, filename):
        # Logic for opening a recent file goes here...
        self.centralWidget.setText(f"<b>{filename}</b> opened")

    def newFile(self):
        # Logic for creating a new file goes here...
        self.centralWidget.setText("<b>File > New</b> clicked")

    def openFile(self):
        # Logic for opening an existing file goes here...
        self.centralWidget.setText("<b>File > Open...</b> clicked")

    def saveFile(self):
        # Logic for saving a file goes here...
        self.centralWidget.setText("<b>File > Save</b> clicked")

    def copyContent(self):
        # Logic for copying content goes here...
        self.centralWidget.setText("<b>Edit > Copy</b> clicked")

    def pasteContent(self):
        # Logic for pasting content goes here...
        self.centralWidget.setText("<b>Edit > Paste</b> clicked")

    def cutContent(self):
        # Logic for cutting content goes here...
        self.centralWidget.setText("<b>Edit > Cut</b> clicked")

    def helpContent(self):
        # Logic for launching help goes here...
        self.centralWidget.setText("<b>Help > Help Content...</b> clicked")

    def about(self):
        # Logic for showing an about dialog content goes here...
        self.centralWidget.setText("<b>Help > About...</b> clicked")

    def populateOpenRecent(self):
        # Step 1. Remove the old options from the menu
        self.openRecentMenu.clear()
        # Step 2. Dynamically create the actions
        actions = []
        filenames = [f"File-{n}" for n in range(5)]
        for filename in filenames:
            action = QAction(filename, self)
            action.triggered.connect(partial(self.openRecentFile, filename))
            actions.append(action)
        # Step 3. Add the actions to the menu
        self.openRecentMenu.addActions(actions)
Exemplo n.º 5
0
class Window(QMainWindow):
    """Main Window."""

    def __init__(self, parent=None):
        """Initializer"""
        super().__init__(parent)
        self.setWindowTitle("Python Menus & Toolbars")
        self.resize(800, 400)
        self.centralWidget = QLabel("Hello, World")
        self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.setCentralWidget(self.centralWidget)
        self._createActions()
        self._createMenuBar()
        self._createToolBars()
        self._createStatusBar()

        # Uncomment the call to ._createContextMenu() below to create a context
        # menu using menu policies. To test this out, you also need to comment
        # out .contextMenuEvent() and uncomment ._createContextMenu()
        # self._createContextMenu()

        self._connectActions()


    def _connectActions(self):
        # Connect File Actions
        self.newAction.triggered.connect(self.newFile)
        self.openAction.triggered.connect(self.openFile)
        self.saveAction.triggered.connect(self.saveFile)
        self.exitAction.triggered.connect(self.close)

        # Connect Edit Actions
        self.copyAction.triggered.connect(self.copyContent)
        self.pasteAction.triggered.connect(self.pasteContent)
        self.cutAction.triggered.connect(self.cutContent)
        self.findAction.triggered.connect(self.findContent)
        self.replaceAction.triggered.connect(self.replaceContent)

        # Connect Help Actions
        self.helpContentAction.triggered.connect(self.helpContent)
        self.aboutAction.triggered.connect(self.about)

        # Connect Open Recent to dynamically populate it
        self.openRecentMenu.aboutToShow.connect(self.populateOpenRecent)


    def _createActions(self):
        # File Actions
        # Create actions using the first constructor
        self.newAction = QAction(self)
        self.newAction.setText("&New")
        self.newAction.setIcon(QIcon(":file-new.svg"))

        # Creating actions using the second constructor
        self.openAction = QAction(QIcon(":file-open.svg"), "&Open...", self)
        self.saveAction = QAction(QIcon(":file-save.svg"), "&Save", self)
        self.exitAction = QAction("&Exit", self)

        # Shortcut keys for the file items
        self.newAction.setShortcut("Ctrl+N")
        self.openAction.setShortcut("Ctrl+O")
        self.saveAction.setShortcut("Ctrl+S")

        # Adding help tips
        newTip = "Create a new file"
        self.newAction.setStatusTip(newTip)
        self.newAction.setToolTip(newTip)
        openTip = "Open an existing file"
        self.openAction.setStatusTip(openTip)
        self.openAction.setToolTip(openTip)
        saveTip = "Save current file"
        self.saveAction.setStatusTip(saveTip)
        self.saveAction.setToolTip(saveTip)
        exitTip = "Exit program"
        self.exitAction.setStatusTip(exitTip)
        self.exitAction.setToolTip(exitTip)

        # Edit Actions
        self.copyAction = QAction(QIcon(":edit-copy.svg"), "&Copy", self)
        self.pasteAction = QAction(QIcon(":edit-paste.svg"), "&Paste", self)
        self.cutAction = QAction(QIcon(":edit-cut.svg"), "C&ut", self)
        self.findAction = QAction("F&ind", self)
        self.replaceAction = QAction("&Replace", self)

        # Adding help tips
        copyTip = "Copy content"
        self.copyAction.setStatusTip(copyTip)
        self.copyAction.setToolTip(copyTip)
        pasteTip = "Paste content"
        self.pasteAction.setStatusTip(pasteTip)
        self.pasteAction.setToolTip(pasteTip)
        cutTip = "Cut content"
        self.cutAction.setStatusTip(cutTip)
        self.cutAction.setToolTip(cutTip)
        findTip = "Find content"
        self.findAction.setStatusTip(findTip)
        self.findAction.setToolTip(findTip)
        replaceTip = "Replace content"
        self.replaceAction.setStatusTip(replaceTip)
        self.replaceAction.setToolTip(replaceTip)

        # Shortcut keys for the edit items (using standard keys)
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.cutAction.setShortcut(QKeySequence.Cut)

        # TODO: Check on the Help Menu title to see why the word 'Help' is not showing
        self.helpContentAction = QAction("&Help Content", self)

        self.aboutAction = QAction("&About", self)

    def _createContextMenu(self):
        self.centralWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.centralWidget.addAction(self.newAction)
        self.centralWidget.addAction(self.openAction)
        self.centralWidget.addAction(self.saveAction)
        self.centralWidget.addAction(self.copyAction)
        self.centralWidget.addAction(self.pasteAction)
        self.centralWidget.addAction(self.cutAction)
        self.centralWidget.addAction(self.findAction)
        self.centralWidget.addAction(self.replaceAction)

    def _createMenuBar(self):
        menuBar = self.menuBar()

        # Creating menus using a QMenu object
        fileMenu = QMenu("&File", self)
        menuBar.addMenu(fileMenu)
        fileMenu.addAction(self.newAction)
        fileMenu.addAction(self.openAction)
        self.openRecentMenu = fileMenu.addMenu("Open Recent")
        fileMenu.addAction(self.saveAction)

        # Add a separator before Exit
        fileMenu.addSeparator()
        fileMenu.addAction(self.exitAction)

        editMenu = menuBar.addMenu("&Edit")
        editMenu.addAction(self.copyAction)
        editMenu.addAction(self.pasteAction)
        editMenu.addAction(self.cutAction)
        editMenu.addSeparator()

        # Find and Replace submenu in the edit menu after a separator
        findMenu = editMenu.addMenu("Find and Replace")
        findMenu.addAction(self.findAction)
        findMenu.addAction(self.replaceAction)

        helpMenu = menuBar.addMenu(QIcon(":help-content.svg"), "&Help")
        helpMenu.addAction(self.helpContentAction)
        helpMenu.addAction(self.aboutAction)

    def _createStatusBar(self):
        self.statusbar = self.statusBar()
        # Adding a temporary message
        self.statusbar.showMessage("Ready", 3000)
        # Adding a permanent message
        self.wcLabel = QLabel(f"{self.getWordCount()} Words")
        self.statusbar.addPermanentWidget(self.wcLabel)

    def _createToolBars(self):
        # File Toolbar
        fileToolBar = self.addToolBar("File")
        fileToolBar.setMovable(False)
        fileToolBar.addAction(self.newAction)
        fileToolBar.addAction(self.openAction)
        fileToolBar.addAction(self.saveAction)

        # Edit Toolbar
        editToolBar = QToolBar("Edit", self)
        self.addToolBar(editToolBar)
        editToolBar.addAction(self.copyAction)
        editToolBar.addAction(self.pasteAction)
        editToolBar.addAction(self.cutAction)

        # Add separator between edit functions and the widgets
        editToolBar.addSeparator()

        # Widgets
        self.fontSizeSpinBox = QSpinBox()
        self.fontSizeSpinBox.setFocusPolicy(Qt.NoFocus)
        editToolBar.addWidget(self.fontSizeSpinBox)

        # commented out this section for the Help Toolbar
        # Using a QToolBar object and a toolbar area
        # helpToolBar = QToolBar("Help", self)
        # self.addToolBar(Qt.LeftToolBarArea, helpToolBar)

    def contextMenuEvent(self, event):
        # Create a menu object with the central widget as parent
        menu = QMenu(self.centralWidget)

        # Populate the menu with actions
        menu.addAction(self.newAction)
        menu.addAction(self.openAction)
        menu.addAction(self.saveAction)

        # add a separator between the file actions and edit actions
        separator = QAction(self)
        separator.setSeparator(True)
        menu.addAction(separator)
        menu.addAction(self.copyAction)
        menu.addAction(self.pasteAction)
        menu.addAction(self.cutAction)

        # Launch the menu
        menu.exec(event.globalPos())

    def getWordCount(self):
        # Logic for computing the word count goes here...
        return 42

    def openRecentFile(self, filename):
        # Logic for opening a recent file goes here...
        self.centralWidget.setText(f"<b>{filename}</b> opened")

    def populateOpenRecent(self):
        # Step 1. Remove the old options from the menu
        self.openRecentMenu.clear()
        # Step 2. Dynamically create  the actions
        actions = []
        filenames = [f"File-{n}" for n in range(5)]
        for filename in filenames:
            action = QAction(filename, self)
            action.triggered.connect(partial(self.openRecentFile, filename))
            actions.append(action)
        # Step 3. Add the actions to the  menu
        self.openRecentMenu.addActions(actions)

    # Slots
    def newFile(self):
        # Logic for creating a new file goes here...
        self.centralWidget.setText("<b>File > New</b> clicked")

    def openFile(self):
        # Logic for opening an existing file goes here...
        self.centralWidget.setText("<b>File > Open...</b> clicked")

    def saveFile(self):
        # Logic for saving a file goes here...
        self.centralWidget.setText("<b>File > Save</b> clicked")

    def copyContent(self):
        # Logic for copying content goes here...
        self.centralWidget.setText("<b>Edit > Copy</b> clicked")

    def pasteContent(self):
        # Logic for pasting content goes here...
        self.centralWidget.setText("<b>Edit > Past</b> clicked")

    def cutContent(self):
        # Logic for cutting content goes here...
        self.centralWidget.setText("<b>Edit > Cut</b> clicked")

    def helpContent(self):
        # Logic for launching help goes here]
        self.centralWidget.setText("<b>Help > Help Content...</b> clicked")

    def about(self):
        # Logic for showing an about dialog content goes here...
        self.centralWidget.setText("<b>Help > About...</b> clicked")

    def findContent(self):
        self.centralWidget.setText("<b>Edit > Find > Find...</b> clicked")

    def replaceContent(self):
        self.centralWidget.setText("<b>Edit > Find > Replace...</b> clicked")
Exemplo n.º 6
0
class Window(QMainWindow):
    # This is the main window (The Top Level Widget)
    def __init__(self, parent=None):
        super().__init__()  # <-- Initializer
        self.setWindowTitle("Python Menus and Toolbars")
        self.resize(400, 200)

        self.centralWidget = QLabel("Hello, World!")
        self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.setCentralWidget(self.centralWidget)

        self._createActions()
        self._createMenuBars()
        self._createToolBars()
        self._createContextMenu()
        # self.contextMenuEvent(self.event)
        self._connectActions()

    def newFile(self):
        # Logic for new file goes here
        self.centralWidget.setText("<b>File > New...</b> clicked")

    def openFile(self):
        # Logic for open file goes here
        self.centralWidget.setText("<b>File > Open...</b> clicked")

    def saveFile(self):
        # Logic for save file goes here
        self.centralWidget.setText("<b>File > Save...</b> clicked")

    def copyContent(self):
        # Logic for copying goes here
        self.centralWidget.setText("<b>Edit > Copy...</b> clicked")

    def pasteContent(self):
        # Logic for pasting goes here
        self.centralWidget.setText("<b>Edit > Paste...</b> clicked")

    def cutContent(self):
        # Logic for cutting goes here
        self.centralWidget.setText("<b>Edit > Cut...</b> clicked")

    def helpContent(self):
        # Logic for launching help goes here
        self.centralWidget.setText("<b>Help > Help Content...</b> clicked")

    def about(self):
        # Logic for showing about dialog content goes here
        self.centralWidget.setText("<b>Help > About...</b> clicked")

    def rgbaSettings(self):
        # Logic for RGBA settings here
        self.centralWidget.setText("<b>Settings > RGBA...</b> clicked")

    def hsloSettings(self):
        # Logic for HSLO settings here
        self.centralWidget.setText("<b>Settings > HSLO...</b> clicked")

    def gammaSettings(self):
        # Logic for Gamma settings here
        self.centralWidget.setText("<b>Settings > Gamma...</b> clicked")

    def highPassSounds(self):
        # Logic for High Pass here
        self.centralWidget.setText(
            "<b>Settings > Sounds > High Pass...</b> clicked")

    def lowPassSounds(self):
        # Logic for Low Pass here
        self.centralWidget.setText(
            "<b>Settings > Sounds > Low Pass...</b> clicked")

    def bandPassSounds(self):
        # Logic for Band Pass here
        self.centralWidget.setText(
            "<b>Settings > Sounds > Band Pass...</b> clicked")

    def spectralAnalyzerSounds(self):
        # Logic for FFT here
        self.centralWidget.setText(
            "<b>Settings > Sounds > Spectral Analyzer...</b> clicked")

    def populateOpenRecent(self):
        # Step 1: Remove the old options from the menu
        self.openRecentMenu.clear()

        # Step 2: Dynamically create the actions
        actions = []
        filenames = [f"File-{n}" for n in range(5)]
        for filename in filenames:
            action = QAction(filename, self)
            action.triggered.connect(partial(self.openRecentFile, filename))
            actions.append(action)

        # Step 3: Add the actions to the menu
        self.openRecentMenu.addActions(actions)

    def openRecentFile(self, filename):
        # Logic for opening a recent file here
        self.centralWidget.setText(
            f"<b>File > Open Recent > {filename}</b> opened...")

    def _createMenuBars(self):
        menuBar = self.menuBar()

        # Creating menus using a QMenu object
        fileMenu = QMenu("&File", self)
        menuBar.addMenu(fileMenu)
        fileMenu.addAction(self.newAction)
        fileMenu.addAction(self.openAction)

        # Adding an "Open Recent" submenu
        self.openRecentMenu = fileMenu.addMenu("Open Recent")
        fileMenu.addAction(self.saveAction)
        fileMenu.addSeparator()
        fileMenu.addAction(self.exitAction)

        settingsMenu = menuBar.addMenu("&Settings")
        settingsMenu.addAction(self.rgbaAction)
        settingsMenu.addAction(self.hsloAction)
        settingsMenu.addAction(self.gammaAction)
        settingsMenu.addSeparator()
        soundsMenu = settingsMenu.addMenu("Sounds")
        soundsMenu.addAction(self.highPassAction)
        soundsMenu.addAction(self.lowPassAction)
        soundsMenu.addAction(self.bandPassAction)
        soundsMenu.addAction(self.spectralAnalyzerAction)

        # For when I can find Icons
        # self.newAction.setIcon(QIcon(":file-new.svg"))
        # self.openAction = QAction(QIcon(":file-open.svg"), "&Open...", self)
        # self.saveAction = QAction(QIcon(":file-save.svg"), "&Save", self)
        # self.copyAction = QAction(QIcon(":edit-copy.svg"), "&Copy", self)
        # self.pasteAction = QAction(QIcon(":edit-paste.svg"), "&Paste", self)
        # self.cutAction = QAction(QIcon(":edit-cut.svg"), "C&ut", self)
        # Creating menus using a title

        # Adding to the Edit menu
        editMenu = menuBar.addMenu("&Edit")
        editMenu.addAction(self.cutAction)
        editMenu.addAction(self.copyAction)
        editMenu.addAction(self.pasteAction)
        editMenu.addSeparator()

        # Adding a Find and Replace submenu to the Edit menu
        findMenu = editMenu.addMenu("Find and Replace")
        findMenu.addAction("Find...")
        findMenu.addAction("Replace...")

        # Adding to the help menu
        helpMenu = menuBar.addMenu("&Help")
        helpMenu.addAction(self.helpContentAction)
        helpMenu.addAction(self.aboutAction)

        # Using an icon and a title
        # helpMenu = menuBar.addMenu("&Help")

    def _createToolBars(self):
        # Using a title
        fileToolBar = self.addToolBar("File")

        # Using a QToolBar object
        editToolBar = QToolBar("Edit", self)
        self.addToolBar(editToolBar)
        editToolBar.addSeparator()
        self.fontSizeSpinBox = QSpinBox()
        self.fontSizeSpinBox.setFocusPolicy(Qt.NoFocus)
        editToolBar.addWidget(self.fontSizeSpinBox)

        # Using a QToolBar object and a toolbar area
        # helpToolBar = QToolBar("Help", self)
        # self.addToolBar(Qt.LeftToolBarArea, helpToolBar)

    def _createActions(self):
        # Creating actions using the constructor QAction(parent)
        self.newAction = QAction(self)
        self.newAction.setText("&New")

        # Creating Actions using the second constructor (parent, text)
        self.openAction = QAction("&Open...", self)
        self.saveAction = QAction("&Save", self)
        self.exitAction = QAction("&Exit", self)
        self.rgbaAction = QAction("&RGBA", self)
        self.hsloAction = QAction("&HSLO", self)
        self.gammaAction = QAction("&Gamma", self)
        self.highPassAction = QAction("&High Pass", self)
        self.lowPassAction = QAction("&Low Pass", self)
        self.bandPassAction = QAction("&Band Pass", self)
        self.spectralAnalyzerAction = QAction("&Spectral Analyzer", self)
        self.copyAction = QAction("&Copy", self)
        self.pasteAction = QAction("&Paste", self)
        self.cutAction = QAction("&Cut", self)
        self.helpContentAction = QAction("&Help Content", self)
        self.aboutAction = QAction("&About", self)

        self.newAction.setShortcut("Ctrl+N")
        self.openAction.setShortcut("Ctrl+O")
        self.saveAction.setShortcut("Ctrl+S")
        self.exitAction.setShortcut("Alt+F4")
        self.rgbaAction.setShortcut("Ctrl+R")
        self.hsloAction.setShortcut("Ctrl+H")
        self.gammaAction.setShortcut("Ctrl+G")
        self.highPassAction.setShortcut("Alt+H")
        self.lowPassAction.setShortcut("Alt+L")
        self.bandPassAction.setShortcut("Alt+B")
        self.spectralAnalyzerAction.setShortcut("Ctrl+Alt+A")
        self.copyAction.setShortcut(QKeySequence.Copy)
        self.pasteAction.setShortcut(QKeySequence.Paste)
        self.cutAction.setShortcut(QKeySequence.Cut)
        self.helpContentAction.setShortcut("Alt+Shift+H")
        self.aboutAction.setShortcut("Alt+Shift+A")

    def _createContextMenu(self):
        # Setting the Context Menu policy
        self.centralWidget.setContextMenuPolicy(Qt.ActionsContextMenu)
        # Here we create a separator action
        separator = QAction(self)
        separator.setSeparator(True)
        # Now we get to populate the widget with actions
        self.centralWidget.addAction(self.newAction)
        self.centralWidget.addAction(self.openAction)
        self.centralWidget.addAction(self.saveAction)
        self.centralWidget.addAction(self.cutAction)
        self.centralWidget.addAction(separator)
        self.centralWidget.addAction(self.copyAction)
        self.centralWidget.addAction(self.pasteAction)

    """
   def contextMenuEvent(self, event):
      # Here we create a menu object with the central widget as parent
      menu = QMenu(self.centralWidget)
      
      # Now we get to populate the menu with actions!
      
      menu.addAction(self.newAction)
      menu.addAction(self.openAction)
      menu.addAction(self.saveAction)
      menu.addAction(self.copyAction)
      menu.addAction(self.pasteAction)
      menu.addAction(self.cutAction)
      
      # Now we launch the menu
      menu.exec(event.globalPos())
      """

    def _connectActions(self):
        # Connect File actions
        self.newAction.triggered.connect(self.newFile)
        self.openAction.triggered.connect(self.openFile)
        self.saveAction.triggered.connect(self.saveFile)
        self.exitAction.triggered.connect(self.close)

        # Connect Settings actions
        self.rgbaAction.triggered.connect(self.rgbaSettings)
        self.hsloAction.triggered.connect(self.hsloSettings)
        self.gammaAction.triggered.connect(self.gammaSettings)
        self.highPassAction.triggered.connect(self.highPassSounds)
        self.lowPassAction.triggered.connect(self.lowPassSounds)
        self.bandPassAction.triggered.connect(self.bandPassSounds)
        self.spectralAnalyzerAction.triggered.connect(
            self.spectralAnalyzerSounds)

        # Connect Edit actions
        self.copyAction.triggered.connect(self.copyContent)
        self.pasteAction.triggered.connect(self.pasteContent)
        self.cutAction.triggered.connect(self.cutContent)

        # Connect Help actions
        self.helpContentAction.triggered.connect(self.helpContent)
        self.aboutAction.triggered.connect(self.about)

        # Adding a dynamic menu
        self.openRecentMenu.aboutToShow.connect(self.populateOpenRecent)