본문 바로가기
PyQt5_

Actions, Toolbars & Menus

by 자동매매 2023. 3. 13.

Toolbars

Qt 도구 모음은 아이콘, 텍스트 표시를 지원하며 표준 Qt 위젯을 포함 할 수도 있습니다.
그러나 버튼의 경우 가장 좋은 방법은 QAction 시스템을 사용하여 도구 모음에 버튼을 배치하는 것입니다.

 

Qt에서 도구 모음은 QToolBar 클래스에서 생성됩니다. 시작하려면 클래스의 인스턴스를 만든 다음 QMainWindow에서 .addToolbar 를 호출하십시오. 문자열을 QToolBar 에 첫 번째 매개 변수로 전달하면 UI에서 도구 모음을 식별하는 데 사용되는 도구 모음의 이름이 설정됩니다.

 

import sys

from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import (
    QApplication,
    QLabel,
    QMainWindow,
    QToolBar,
)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        label = QLabel("Hello!")
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.setCentralWidget(label)

        toolbar = QToolBar("My main toolbar")
        self.addToolBar(toolbar)

    def onMyToolBarButtonClick(self, s):
        print("click", s)




app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()

상단에 얇은 회색 막대가 표시됩니다도구 모음. 마우스 오른쪽 버튼을 클릭하고 이름을 클릭하여 끕니다.

 

도구 모음을 좀 더 흥미롭게 만들어 보겠습니다.
QButton
위젯을 추가 할 수도 있지만 Qt에는 멋진 기능을 제공하는 더 나은 접근 방식이 있으며 QAction을 통한 것입니다. QAction은 추상 사용자 인터페이스를 설명하는 방법을 제공하는 클래스입니다.
단일 객체 내에서 여러 인터페이스 요소를 정의 할 수 있으며 해당 요소와 상호 작용하는 효과로 통합 될 수 있다는 것입니다. 예를 들어, 툴바뿐만 아니라 메뉴에도 표시되는 함수를 갖는 것이 일반적입니다 

QAction이 없으면 여러 위치에서 이를 정의해야합니다. 그러나 QAction을 사용하면 단일 QAction을 정의하고 트리거 된 작업을 정의한 다음 이 작업을 메뉴와 도구 모음에 추가 할 수 있습니다.
QAction에는 연결할 수있는 이름, 상태 메시지, 아이콘 및 신호가 있습니다.

 

첫 번째 QAction을 추가하는 방법은 아래 코드를 참조하십시오.

import sys

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QAction
from PyQt6.QtWidgets import (
    QApplication,
    QLabel,
    QMainWindow,
    QToolBar,
)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        label = QLabel("Hello!")
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.setCentralWidget(label)

        toolbar = QToolBar("My main toolbar")
        self.addToolBar(toolbar)

        button_action = QAction("Your button", self) # 첫째인자 - text/icon, 둘째인자 - parent객체
        button_action.setStatusTip("This is your button")  # 상태바에 표시될 내용 지정
        button_action.triggered.connect(self.onMyToolBarButtonClick)
        toolbar.addAction(button_action)

    def onMyToolBarButtonClick(self, s):
        print("click", s)




app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()

The signal passed indicates whether the action is checked -> checkable 비활성화로 계속 False 전달

 

# 상태바 표시 ->  setStatusTip 설정 값 표시, button_action hover 시 표시

self.setStatusBar(QStatusBar(self))

 

# clickable 설정

다음으로 QAction 토글 가능을 켜서 클릭하면 켜지고 다시 클릭하면 꺼집니다. 이를 위해 QAction 객체에 대해 setCheckable(True)를 호출하기만 하면 됩니다.

button_action.setCheckable(True)

.toggled 신호도 있는데, 이는 버튼이 전환될때  신호를 방출합니다. 그러나 효과는 동일

button_action.triggered.connect(self.onMyToolBarButtonClick)

7.4 toolbars_and_menus_4.py
0.00MB

 

# Icon 추가

        toolbar = QToolBar("My main toolbar")
        toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(toolbar)

        button_action = QAction(QIcon(파일명,"Your button",self,)

Qt는 운영 체제 기본 설정을 사용하여 도구 모음에 아이콘, 텍스트 또는 아이콘과 텍스트를 표시할지 여부를 결정합니다. 그러나 .setToolButtonStyle을 사용하여 이를 재정의할 수 있습니다. 이 슬롯은 Qt. 네임 스페이스에서 다음 플래그 중 하나를 허용합니다.

Flag Behavior
Qt.ToolButtonStyle.ToolButtonIconOnly Icon only, no text
Qt.ToolButtonStyle.ToolButtonTextOnly Text only, no icon
Qt.ToolButtonStyle.ToolButtonTextBesideIcon Icon and text, with text beside
the icon  
Qt.ToolButtonStyle.ToolButtonTextUnderIcon Icon and text, with text under
the icon  
Qt.ToolButtonStyle.ToolButtonFollowStyle Follow the host desktop style

기본값은 Qt.ToolButtonStyle.ToolButtonFollowStyle이며, 이는 응용 프로그램이 기본적으로 응용 프로그램이 실행되는 데스크톱의 표준 / 전역 설정을 따른다는 것을 의미합니다. 이는 일반적으로 응용 프로그램이 가능한 네이티브한 느낌을 주기 위해 권장됩니다.

 

# seperator 추가

# widget 추가

        toolbar.addSeparator()

        toolbar.addWidget(QLabel("Hello"))
        toolbar.addWidget(QCheckBox())

 

import os
import sys

from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtWidgets import (
    QApplication,
    QCheckBox,
    QLabel,
    QMainWindow,
    QStatusBar,
    QToolBar,
)

basedir = os.path.dirname(__file__)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        label = QLabel("Hello!")
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.setCentralWidget(label)

        toolbar = QToolBar("My main toolbar")
        toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(toolbar)

        button_action = QAction(
            QIcon(os.path.join(basedir, "bug.png")),
            "Your button",
            self,
        )
        button_action.setStatusTip("This is your button")
        button_action.triggered.connect(self.onMyToolBarButtonClick)
        button_action.setCheckable(True)
        toolbar.addAction(button_action)

        toolbar.addSeparator()

        button_action2 = QAction(
            QIcon(os.path.join(basedir, "bug.png")),
            "Your button2",
            self,
        )
        button_action2.setStatusTip("This is your button2")
        button_action2.triggered.connect(self.onMyToolBarButtonClick)
        button_action2.setCheckable(True)
        toolbar.addAction(button_action2)

        toolbar.addWidget(QLabel("Hello"))
        toolbar.addWidget(QCheckBox())

        self.setStatusBar(QStatusBar(self))

    def onMyToolBarButtonClick(self, s):
        print("click", s)

7.6 toolbars_and_menus_6.py
0.00MB
bug.png
0.00MB

 

 

Menu

메뉴를 만들기 위해 QMainWindow에서 .menuBar()라는 메뉴 모음을 만듭니다. 메뉴 이름을 전달하면서 .addMenu()를 호출하여 메뉴 표시줄에 메뉴를 추가합니다.

quick key : &추가 - Alt키 사용

 

basic/toolbars_and_menus_7.py

import os
import sys

from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtWidgets import (
    QApplication,
    QCheckBox,
    QLabel,
    QMainWindow,
    QStatusBar,
    QToolBar,
)

basedir = os.path.dirname(__file__)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        label = QLabel("Hello!")
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.setCentralWidget(label)

        toolbar = QToolBar("My main toolbar")
        toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(toolbar)

        button_action = QAction(
            QIcon(os.path.join(basedir, "bug.png")),
            "&Your button",
            self,
        )
        button_action.setStatusTip("This is your button")
        button_action.triggered.connect(self.onMyToolBarButtonClick)
        button_action.setCheckable(True)
        toolbar.addAction(button_action)

        toolbar.addSeparator()

        button_action2 = QAction(
            QIcon(os.path.join(basedir, "bug.png")),
            "Your &button2",
            self,
        )
        button_action2.setStatusTip("This is your button2")
        button_action2.triggered.connect(self.onMyToolBarButtonClick)
        button_action2.setCheckable(True)
        toolbar.addAction(button_action2)

        toolbar.addWidget(QLabel("Hello"))
        toolbar.addWidget(QCheckBox())

        self.setStatusBar(QStatusBar(self))

        menu = self.menuBar()

        file_menu = menu.addMenu("&File")
        file_menu.addAction(button_action)

    def onMyToolBarButtonClick(self, s):
        print("click", s)




app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()

basic/toolbars_and_menus_8.py

        file_menu = menu.addMenu("&File")
        file_menu.addAction(button_action)
        file_menu.addSeparator()
        file_menu.addAction(button_action2)

basic/toolbars_and_menus_9.py

        menu = self.menuBar()

        file_menu = menu.addMenu("&File")
        file_menu.addAction(button_action)
        file_menu.addSeparator()

        file_submenu = file_menu.addMenu("Submenu")
        file_submenu.addAction(button_action2)

 

basic/toolbars_and_menus_end.py

 

        button_action.setShortcut(QKeySequence("Ctrl+p"))

 

import os
import sys

from PyQt6.QtCore import QSize, Qt
from PyQt6.QtGui import QAction, QIcon, QKeySequence
from PyQt6.QtWidgets import (
    QApplication,
    QCheckBox,
    QLabel,
    QMainWindow,
    QStatusBar,
    QToolBar,
)

basedir = os.path.dirname(__file__)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        label = QLabel("Hello!")

        # The `Qt` namespace has a lot of attributes to customize
        # widgets. See: http://doc.qt.io/qt-5/qt.html
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        # Set the central widget of the Window. Widget will expand
        # to take up all the space in the window by default.
        self.setCentralWidget(label)

        toolbar = QToolBar("My main toolbar")
        toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(toolbar)

        button_action = QAction(
            QIcon(os.path.join(basedir, "bug.png")),
            "&Your button",
            self,
        )
        button_action.setStatusTip("This is your button")
        button_action.triggered.connect(self.onMyToolBarButtonClick)
        button_action.setCheckable(True)
        # You can enter keyboard shortcuts using key names (e.g. Ctrl+p)
        # Qt.namespace identifiers (e.g. Qt.CTRL + Qt.Key_P)
        # or system agnostic identifiers (e.g. QKeySequence.Print)
        button_action.setShortcut(QKeySequence("Ctrl+p"))
        toolbar.addAction(button_action)

        toolbar.addSeparator()

        button_action2 = QAction(
            QIcon(os.path.join(basedir, "bug.png")),
            "Your &button2",
            self,
        )
        button_action2.setStatusTip("This is your button2")
        button_action2.triggered.connect(self.onMyToolBarButtonClick)
        button_action2.setCheckable(True)
        toolbar.addAction(button_action)

        toolbar.addWidget(QLabel("Hello"))
        toolbar.addWidget(QCheckBox())

        self.setStatusBar(QStatusBar(self))

        menu = self.menuBar()

        file_menu = menu.addMenu("&File")
        file_menu.addAction(button_action)

        file_menu.addSeparator()

        file_submenu = file_menu.addMenu("Submenu")

        file_submenu.addAction(button_action2)

    def onMyToolBarButtonClick(self, s):
        print("click", s)




app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()

 

 

 

'PyQt5_' 카테고리의 다른 글

Windows  (0) 2023.03.13
Dialogs  (0) 2023.03.13
Layouts  (0) 2023.03.11
Widgets  (0) 2023.03.10
Signals & Slots  (0) 2023.03.10

댓글