QSplashScreen.setPixmap导致启动屏返回默认位置的技术问询
解决QSplashScreen调用setPixmap后回到默认显示器的问题
这个问题我之前也碰到过——调用setPixmap()后QSplashScreen跑回默认显示器,本质是因为设置新pixmap时,QSplashScreen会重新调整窗口的几何属性,导致位置被重置到主屏幕。这里有两个靠谱的解决办法:
方法一:更新Pixmap后重新设置位置
每次调用setPixmap()后,手动重新计算第二屏幕的中心位置并移动窗口,这样就能把启动屏拉回目标显示器。我们可以把移动逻辑封装成方法,方便复用:
class SplashScreen(QSplashScreen): def __init__(self): self._pixmap = QPixmap("test1.png") super(SplashScreen, self).__init__(self._pixmap) self._target_screen = 1 # 把目标屏幕索引存为实例变量,避免重复写死 self.move_to_target_screen() def move_to_target_screen(self): """封装移动到目标屏幕中心的逻辑""" scr = qApp.desktop().screenGeometry(self._target_screen) self.move(scr.center() - self.rect().center()) def drawSomething(self): # 创建要添加的内容Pixmap add_pixmap = QPixmap(...) # 替换成你的实际创建逻辑 # 基于原Pixmap创建新的Pixmap并绘制内容 new_pixmap = self._pixmap.copy() painter = QPainter(new_pixmap) painter.drawPixmap(0, 0, add_pixmap) # 调整坐标到你需要的位置 painter.end() # 更新Pixmap self.setPixmap(new_pixmap) # 重新移动到目标屏幕中心 self.move_to_target_screen()
方法二:直接在窗口上绘制(更优雅)
不需要替换整个Pixmap,直接用QPainter在QSplashScreen窗口上绘制内容,然后调用update()刷新。这种方式不会触发窗口位置的重置,是更优的方案:
class SplashScreen(QSplashScreen): def __init__(self): self._pixmap = QPixmap("test1.png") super(SplashScreen, self).__init__(self._pixmap) screen = 1 scr = qApp.desktop().screenGeometry(screen) self.move(scr.center() - self.rect().center()) def drawSomething(self): # 创建要添加的内容Pixmap add_pixmap = QPixmap(...) # 替换成你的实际创建逻辑 # 直接在窗口上绘制 painter = QPainter(self) painter.drawPixmap(50, 50, add_pixmap) # 坐标根据需求调整 painter.end() # 刷新窗口显示 self.update()
为什么方法二更推荐?
它不需要重新创建整个Pixmap,也不会触发QSplashScreen内部的位置重置逻辑,既能保持启动屏在第二显示器的位置,又能高效地更新显示内容。
内容的提问来源于stack exchange,提问作者Skandix
相关产品推荐
相关产品推荐

