QMainWindow常用(二)

QAction设置和连接

  • setIcon() 为动作设置图标;
  • setText() 设置文本
  • setShortcut() 设置快捷键
  • 为测试快捷键的效果,在类中加入了test函数,按下Ctrl+1快捷键时,将在控制台输出"OK"。
import sys

from PySide6.QtCore import Slot
from PySide6.QtGui import QAction, QPixmap
from PySide6.QtWidgets import QApplication, QMainWindow, QMenu


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

        menu_bar = self.menuBar()
        menu_file = QMenu("&File")
        menu_bar.addMenu(menu_file)

        # 创建动作
        self.act_file_new = QAction("&New")

        # 动作加入菜单
        menu_file.addAction(self.act_file_new)
        self.act_file_new.setIcon(QPixmap("1.png"))
        self.act_file_new.setShortcut("CTRL+1")

        self.act_file_new.triggered.connect(self.test)

    @Slot()
    def test(self):
        print("OK")


if __name__ == "__main__":
    app = QApplication()
    w = MainWindow()
    w.show()
    sys.exit(app.exec())

运行效果如下:


image.png

将动作加入工具栏

  • 使用QToolBar()创建工具栏;
  • 使用QMainWindow.addToolBar() 将将工具栏加入窗口;
  • 使用QToolBar.addAction() 为工具栏添加动作;
  • 创建工具栏时可以指定位置:
    • 位置参数如下:LeftToolBarArea,RightToolBarArea,TopToolBarArea,BottomToolBarArea,AllToolBarAreas
    • setFloatable() 方法可以指定工具栏浮动;
    • addSeparator() 可以在工具栏中插入分隔线;
      代码如下(在上例中的init最后加入如下代码):
        tool_bar = QToolBar("工具栏")
        self.addToolBar(Qt.ToolBarArea.TopToolBarArea, tool_bar)
        tool_bar.setFloatable(True)

        tool_bar.addAction(self.act_file_new)

运行效果如下:


运行效果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容