pyqt 横竖屏切换

目录

[横竖屏切换 待测试方法:](#横竖屏切换 待测试方法:)

发现关键是:

方法2:重新打开图片,刷新界面:


横竖屏切换 待测试方法:

python 复制代码
self.setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)  # 取消固定大小
self.setWindowFlags(Qt.Widget)
self.show()

# 再重新设置
self.setWindowFlags(Qt.FramelessWindowHint)
self.setFixedSize(new_w, new_h)
self.show()

好像也可以:

python 复制代码
import sys
import subprocess
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QFont


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

        # 获取屏幕分辨率
        screen = QApplication.primaryScreen().geometry()
        self.original_width = screen.width()
        self.original_height = screen.height()

        self.current_orientation = 'landscape'
        self.display_name = self.get_display_name()

        self.initUI()
        self.setFullscreenGeometry('landscape')

    def get_display_name(self):
        """获取主显示器名称"""
        try:
            result = subprocess.run(["xrandr"], capture_output=True, text=True)
            for line in result.stdout.split('\n'):
                if " connected" in line:
                    return line.split()[0]
        except Exception as e:
            print(f"获取显示器名称失败: {e}")
        return "eDP-1"

    def initUI(self):
        """初始化界面"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        layout = QVBoxLayout(central_widget)

        # 创建标签
        title_label = QLabel("全屏横竖屏切换演示")
        self.orientation_label = QLabel("当前: 横屏模式")
        self.resolution_label = QLabel(f"分辨率: {self.original_width}x{self.original_height}")

        # 设置标签对齐
        for label in [title_label, self.orientation_label, self.resolution_label]:
            label.setAlignment(Qt.AlignCenter)

        # 创建按钮
        switch_btn = QPushButton("切换横竖屏")
        exit_btn = QPushButton("退出程序")

        switch_btn.clicked.connect(self.toggleOrientation)
        exit_btn.clicked.connect(self.close)

        # 布局
        layout.addStretch()
        layout.addWidget(title_label)
        layout.addWidget(self.orientation_label)
        layout.addWidget(self.resolution_label)
        layout.addStretch()

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(switch_btn)
        button_layout.addWidget(exit_btn)
        button_layout.addStretch()

        layout.addLayout(button_layout)
        layout.addStretch()

        # 简单样式
        self.setStyleSheet("background-color: #2b2b2b; color: white;")

    def setFullscreenGeometry(self, orientation):
        """设置全屏"""
        self.current_orientation = orientation

        if orientation == 'landscape':
            width, height = self.original_width, self.original_height
            text, bg_color, rotate_cmd = "横屏模式", "#2b2b2b", "normal"
        else:
            width, height = self.original_height, self.original_width
            text, bg_color, rotate_cmd = "竖屏模式", "#1e3d59", "left"

        print(f"切换到{text}: {width}x{height}")

        # 执行屏幕旋转
        try:
            subprocess.run(["xrandr", "--output", self.display_name, "--rotate", rotate_cmd], capture_output=True, timeout=5)
        except Exception as e:
            print(f"屏幕旋转出错: {e}")

        # 延迟设置窗口
        QTimer.singleShot(1000, lambda: self.applySettings(width, height, text, bg_color))

    def applySettings(self, width, height, text, bg_color):
        QWIDGETSIZE_MAX = 16777215
        self.setFixedSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)  # 取消固定大小
        self.setWindowFlags(Qt.Widget)


        self.show()
        
        # 再重新设置
        # self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        
        self.setFixedSize(width, height)
        self.show()

    def toggleOrientation(self):
        """切换横竖屏"""
        if self.current_orientation == 'landscape':
            self.setFullscreenGeometry('portrait')
        else:
            self.setFullscreenGeometry('landscape')


if __name__ == '__main__':
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

解决方法是,重新创建界面并显示。

发现关键是:

applySettings 里面需要更新一下ui。

全屏参数不影响?

repaint 不能解决 更新ui控件和设置样式都需要。

python 复制代码
    def applySettings(self, width, height, text, bg_color):
        """应用窗口设置"""
        self.hide()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setGeometry(0, 0, width, height)
        self.setFixedSize(width, height)
        self.move(0, 0)

        self.setStyleSheet(f"background-color: {bg_color}; color: white;")
        self.orientation_label.setText(f"当前: {text}")
        self.resolution_label.setText(f"分辨率: {width}x{height}")

too_sys/hengshu_new.py

python 复制代码
import sys
import subprocess
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QFont


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

        # 获取屏幕分辨率
        screen = QApplication.primaryScreen().geometry()
        self.original_width = screen.width()
        self.original_height = screen.height()

        self.current_orientation = 'landscape'
        self.display_name = self.get_display_name()

        self.initUI()
        self.setFullscreenGeometry('landscape')

    def get_display_name(self):
        """获取主显示器名称"""
        try:
            result = subprocess.run(["xrandr"], capture_output=True, text=True)
            for line in result.stdout.split('\n'):
                if " connected" in line:
                    return line.split()[0]
        except Exception as e:
            print(f"获取显示器名称失败: {e}")
        return "eDP-1"

    def initUI(self):
        """初始化界面"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        layout = QVBoxLayout(central_widget)

        # 创建标签
        title_label = QLabel("全屏横竖屏切换演示")
        self.orientation_label = QLabel("当前: 横屏模式")
        self.resolution_label = QLabel(f"分辨率: {self.original_width}x{self.original_height}")

        # 设置标签对齐
        for label in [title_label, self.orientation_label, self.resolution_label]:
            label.setAlignment(Qt.AlignCenter)

        # 创建按钮
        switch_btn = QPushButton("切换横竖屏")
        exit_btn = QPushButton("退出程序")

        switch_btn.clicked.connect(self.toggleOrientation)
        exit_btn.clicked.connect(self.close)

        # 布局
        layout.addStretch()
        layout.addWidget(title_label)
        layout.addWidget(self.orientation_label)
        layout.addWidget(self.resolution_label)
        layout.addStretch()

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(switch_btn)
        button_layout.addWidget(exit_btn)
        button_layout.addStretch()

        layout.addLayout(button_layout)
        layout.addStretch()

        # 简单样式
        self.setStyleSheet("background-color: #2b2b2b; color: white;")

    def setFullscreenGeometry(self, orientation):
        """设置全屏"""
        self.current_orientation = orientation

        if orientation == 'landscape':
            width, height = self.original_width, self.original_height
            text, bg_color, rotate_cmd = "横屏模式", "#2b2b2b", "normal"
        else:
            width, height = self.original_height, self.original_width
            text, bg_color, rotate_cmd = "竖屏模式", "#1e3d59", "left"

        print(f"切换到{text}: {width}x{height}")

        # 执行屏幕旋转
        try:
            subprocess.run(["xrandr", "--output", self.display_name, "--rotate", rotate_cmd], capture_output=True, timeout=5)
        except Exception as e:
            print(f"屏幕旋转出错: {e}")

        # 延迟设置窗口
        QTimer.singleShot(1000, lambda: self.applySettings(width, height, text, bg_color))

    def applySettings(self, width, height, text, bg_color):
        """应用窗口设置"""
        self.hide()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setGeometry(0, 0, width, height)
        self.setFixedSize(width, height)
        self.move(0, 0)

        self.setStyleSheet(f"background-color: {bg_color}; color: white;")
        self.orientation_label.setText(f"当前: {text}")
        self.resolution_label.setText(f"分辨率: {width}x{height}")

        self.show()

    def toggleOrientation(self):
        """切换横竖屏"""
        if self.current_orientation == 'landscape':
            self.setFullscreenGeometry('portrait')
        else:
            self.setFullscreenGeometry('landscape')


if __name__ == '__main__':
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

方法2:重新打开图片,刷新界面:

python 复制代码
import sys
import subprocess
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout,
    QHBoxLayout, QPushButton, QLabel
)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QPixmap


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

        # 获取屏幕分辨率
        screen = QApplication.primaryScreen().geometry()
        self.original_width = screen.width()
        self.original_height = screen.height()

        self.current_orientation = 'landscape'
        self.display_name = self.get_display_name()

        self.initUI()
        self.setFullscreenGeometry('landscape')

    def get_display_name(self):
        """获取主显示器名称"""
        try:
            result = subprocess.run(["xrandr"], capture_output=True, text=True)
            for line in result.stdout.split('\n'):
                if " connected" in line:
                    return line.split()[0]
        except Exception as e:
            print(f"获取显示器名称失败: {e}")
        return "eDP-1"

    def initUI(self):
        """初始化界面"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        layout = QVBoxLayout(central_widget)

        # 创建标签
        title_label = QLabel("全屏横竖屏切换演示")
        self.orientation_label = QLabel("当前: 横屏模式")
        self.resolution_label = QLabel(f"分辨率: {self.original_width}x{self.original_height}")

        # 图片标签(默认隐藏)
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setVisible(False)

        # 设置标签对齐
        for label in [title_label, self.orientation_label, self.resolution_label]:
            label.setAlignment(Qt.AlignCenter)

        # 创建按钮
        switch_btn = QPushButton("切换横竖屏")
        show_img_btn = QPushButton("显示图片")
        exit_btn = QPushButton("退出程序")

        switch_btn.clicked.connect(self.toggleOrientation)
        show_img_btn.clicked.connect(self.toggleImage)
        exit_btn.clicked.connect(self.close)

        # 布局
        layout.addStretch()
        layout.addWidget(title_label)
        layout.addWidget(self.orientation_label)
        layout.addWidget(self.resolution_label)
        layout.addWidget(self.image_label)
        layout.addStretch()

        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(switch_btn)
        button_layout.addWidget(show_img_btn)
        button_layout.addWidget(exit_btn)
        button_layout.addStretch()

        layout.addLayout(button_layout)
        layout.addStretch()

        # 样式
        self.setStyleSheet("background-color: #2b2b2b; color: white;")

    def setFullscreenGeometry(self, orientation):
        """设置全屏"""
        self.current_orientation = orientation

        if orientation == 'landscape':
            width, height = self.original_width, self.original_height
            text, bg_color, rotate_cmd = "横屏模式", "#2b2b2b", "normal"
        else:
            width, height = self.original_height, self.original_width
            text, bg_color, rotate_cmd = "竖屏模式", "#1e3d59", "left"

        print(f"切换到{text}: {width}x{height}")

        # 执行屏幕旋转
        try:
            subprocess.run(["xrandr", "--output", self.display_name, "--rotate", rotate_cmd],
                           capture_output=True, timeout=5)
        except Exception as e:
            print(f"屏幕旋转出错: {e}")

        # 延迟设置窗口
        QTimer.singleShot(1000, lambda: self.applySettings(width, height, text, bg_color))

    def applySettings(self, width, height, text, bg_color):
        """应用窗口设置"""
        self.hide()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setGeometry(0, 0, width, height)
        self.setFixedSize(width, height)
        self.move(0, 0)

        # self.setStyleSheet(f"background-color: {bg_color}; color: white;")

        pixmap = QPixmap("/home/yklele/pic/resize.jpg")
        if pixmap.isNull():
            self.image_label.setText("未找到 example.jpg 图片文件")
        else:
            scaled = pixmap.scaled(self.width() // 2, self.height() // 2, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.image_label.setPixmap(scaled)
        self.image_label.setVisible(True)

        # self.orientation_label.setText(f"当前: {text}")
        # self.resolution_label.setText(f"分辨率: {width}x{height}")

        self.show()

    def toggleOrientation(self):
        """切换横竖屏"""
        if self.current_orientation == 'landscape':
            self.setFullscreenGeometry('portrait')
        else:
            self.setFullscreenGeometry('landscape')

    def toggleImage(self):
        """显示或隐藏图片"""
        if self.image_label.isVisible():
            self.image_label.setVisible(False)
        else:
            pixmap = QPixmap("/home/yklele/pic/resize.jpg")
            if pixmap.isNull():
                self.image_label.setText("未找到 example.jpg 图片文件")
            else:
                scaled = pixmap.scaled(
                    self.width() // 2,
                    self.height() // 2,
                    Qt.KeepAspectRatio,
                    Qt.SmoothTransformation
                )
                self.image_label.setPixmap(scaled)
            self.image_label.setVisible(True)


if __name__ == '__main__':
    if hasattr(Qt, 'AA_EnableHighDpiScaling'):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())
相关推荐
GIS阵地1 小时前
Qt实现简易仪表盘
开发语言·c++·qt·pyqt·qgis·qt5·地理信息系统
懷淰メ17 小时前
【AI加持】基于PyQt5+YOLOv8+DeepSeek的水体污染检测系统(详细介绍)
yolo·目标检测·计算机视觉·pyqt·检测系统·deepseek·水体污染
ctgu9020 小时前
PyQt5(九):如何在Qtdesigner中设置图片
qt·pyqt
weixin_462446231 天前
PyQt 与 Flask 融合:实现桌面端一键启动/关闭 Web 服务的应用
前端·flask·pyqt
懷淰メ2 天前
【AI加持】基于PyQt5+YOLOv8+DeepSeek的输电隐患检测系统(详细介绍)
yolo·目标检测·计算机视觉·pyqt·deepseek·监测系统·输电隐患
大雾的小屋2 天前
【1-1】基于深度学习的滚动轴承故障诊断系统:从数据处理到交互式界面全流程解析
人工智能·pytorch·深度学习·系统架构·人机交互·pyqt·用户界面
赤鸢QAQ3 天前
PyQt qfluentwidgets使用SegoeIcons
pyqt
懷淰メ3 天前
【AI加持】基于PyQt5+YOLOv8+DeepSeek的结核杆菌检测系统(详细介绍)
yolo·目标检测·计算机视觉·pyqt·deepseek·ai分析·结核杆菌
En^_^Joy6 天前
PyQt常用控件使用介绍:QTreeWidget树结构
python·pyqt
懷淰メ11 天前
python3GUI--【AI加持】基于PyQt5+YOLOv8+DeepSeek的智能球体检测系统:(详细介绍)
yolo·目标检测·计算机视觉·pyqt·检测系统·deepseek·球体检测