如何在树莓派外接屏上将PyQt5应用设置为竖屏显示?
实现PyQt5 QMainWindow竖屏显示(树莓派外接屏)
问题分析
你当前代码已设置固定竖屏宽高(480x800),但直接调用showFullScreen()易导致窗口被横屏屏幕拉伸变形,且子控件无法自适应竖屏布局。以下是仅通过调整QMainWindow的优化方案,确保应用及所有子控件自动适配竖屏。
优化代码
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QLabel from PyQt5.QtCore import Qt from PyQt5.QtGui import QScreen class TitleScreen(QWidget): def __init__(self): super().__init__() # 用布局管理器保证子控件自适应竖屏尺寸 layout = QVBoxLayout() self.title_label = QLabel("Saaf 主界面") self.title_label.setAlignment(Qt.AlignCenter) self.title_label.setStyleSheet("font-size: 24px; color: white;") layout.addWidget(self.title_label) self.setLayout(layout) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Saaf") # 获取屏幕信息,自动计算竖屏分辨率(兼容不同尺寸屏幕) screen = QApplication.primaryScreen() screen_geo = screen.availableGeometry() # 横屏转竖屏:互换屏幕宽高 portrait_w = screen_geo.height() portrait_h = screen_geo.width() # 如需固定自定义竖屏尺寸,可替换为下面两行 # portrait_w = 480 # portrait_h = 800 # 固定窗口为竖屏尺寸,避免拉伸变形 self.setFixedSize(portrait_w, portrait_h) # 设置无边框、置顶属性 self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) # 优化样式表,让背景图自适应竖屏窗口 self.setStyleSheet( """ QMainWindow { background-color: #51b09f; background-image: url('Images/icons10-recycle-500.png'); background-repeat: no-repeat; background-position: center; background-size: contain; /* 背景图自适应窗口尺寸 */ } """ ) # 挂载主界面,依赖布局实现子控件自适应 self.screen1 = TitleScreen() self.setCentralWidget(self.screen1) # 将竖屏窗口居中显示在横屏屏幕上(避免全屏拉伸) center_x = (screen_geo.width() - portrait_w) // 2 center_y = (screen_geo.height() - portrait_h) // 2 self.move(center_x, center_y) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() # 若屏幕支持竖屏分辨率,可替换为window.showFullScreen() window.show() sys.exit(app.exec_())
关键调整点
- 动态适配屏幕:通过
QScreen获取屏幕参数,自动计算竖屏尺寸,摆脱硬编码限制。 - 布局管理器:子控件容器(如
TitleScreen)使用布局类,确保控件随窗口尺寸自动调整位置和大小。 - 背景图优化:样式表添加
background-size: contain;,避免背景图在竖屏窗口中拉伸变形。 - 窗口定位:将竖屏窗口居中放置在横屏屏幕上,避免直接全屏导致的内容变形;确认屏幕支持目标竖屏分辨率后,再使用
showFullScreen()。
内容的提问来源于stack exchange,提问作者Abdul Wahhab
相关产品推荐
相关产品推荐

