使用pyqt5设计窗口打包成exe文件后,在其它电脑运行时,出现文字大小会跟随当前机器分辨率变化,以及窗口中控件移位,与本地调试时不一致;
控件移位
字体大小变样
解决方法:
1、在窗口设置中设置窗口的固定大小 ;
main_window.setFixedSize(1116, 601) # 设置窗口的固定大小为1116X601 像素
def retranslateUi(self, main_window):
_translate = QtCore.QCoreApplication.translate
main_window.setWindowIcon(QtGui.QIcon('window_logo.ico'))
main_window.setFixedSize(1116, 601) # 设置窗口的固定大小为1116X601 像素
main_window.setWindowTitle(_translate("main_window", "接口监测系统"))
self.login_logo.setText(_translate("main_window", "TextLabel"))
self.login_title.setText(_translate("main_window", "接 口 监 测 系 统"))
self.login_button.setText(_translate("main_window", "登 录"))
self.new_user.setText(_translate("main_window", "账号注册"))
self.contact_admin.setText(_translate("main_window", "联系管理员"))
self.background_logo.setText(_translate("main_window", "TextLabel"))
2、在对应的控件设计中,设置固定字体的像素大小;
font.setPixelSize(34) # 固定字体像素大小,控制分辨率变化
self.login_title = QtWidgets.QLabel(self.login_frame)
self.login_title.setGeometry(QtCore.QRect(50, 130, 281, 51))
font = QtGui.QFont(font_family)
# font.setPointSize(36) # 正常设定字体大小
font.setPixelSize(34) # 固定字体像素大小,控制分辨率变化
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
font.setStrikeOut(False)
font.setStyleStrategy(QtGui.QFont.PreferAntialias)
self.login_title.setFont(font)
self.login_title.setStyleSheet("color: rgb(0, 0, 127);
self.login_title.setObjectName("login_title")
注意:代码中font = QtGui.QFont(font_family)应用了其它字体资源文件,如果代码中有引用到其它字体文件时,在打包exe文件时,记得把字体的资源文件一并打包。若你使用的字体在运行机器中没有的话,则会用运行机器本级默认的字体,所以不同的字体在不同的电脑中展示不同。
3、设置后,重新打包,则会正常展示,当分辨率改变时,窗口内容也不会有变化;
4、如果不行可以尝试直接在程序的入口添加QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
设置字体大小自适应分辨率
if __name__ == "__main__":
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
MainWin = Login_Window()
MainWin.show()
sys.exit(app.exec_())
或在UI页面元素文件中设置DPI固定值
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
QApplication.setAttribute(Qt.AA_Use96Dpi) # 设置DPI为固定值96
有疑问欢迎评论留意!!
亲测有效,制作不易,你的点赞是小菜更新的动力,点个赞加个关注吧~
关注我,分享更多项目实际案例问题,帮您解决更多问题,少走弯路!!