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_())
相关推荐
wuyk5551 天前
Python办公自动化-第01讲-环境搭建与自动化认知
python·自动化·pyqt
小灰灰搞电子2 天前
PyQt简介
pyqt
wuyk55517 天前
PyQt6-第15讲-数据可视化QChart
python·ui·信息可视化·pyqt
wuyk5551 个月前
PyQt6-第10讲-PDF工具箱
python·microsoft·pdf·pyqt
wuyk5551 个月前
PyQt6-第14讲-数据库与Excel双向同步
数据库·python·ui·excel·pyqt
MrWind灬1 个月前
我给自己写了个 Kafka 桌面客户端:MrWindKafkaClient
kafka·pyqt
万粉变现经纪人1 个月前
如何解决 pip install 安装报错 检测到 yanked 版本需更换可用版本 问题
人工智能·python·scrapy·numpy·pandas·pyqt·pip
MoRanzhi12031 个月前
第6篇(下)· 使用 PyQt5 实现 2048 高性能计算版:统一运行控制与跨模式安全交接
python·pyqt·进程管理·状态机·软件架构·并发控制·数据一致性
wuyk5551 个月前
PyQt6-第06讲-主窗口框架
python·pyqt
MoRanzhi12031 个月前
第6篇(中)· 使用 PyQt5 实现 2048 高性能计算版:无头后台求解与三档运行模式
python·pyqt·数据持久化·多进程·进程间通讯·后台任务·断点续跑