Skip to content

Commit

Permalink
Solve Windows 10 High DPI Problem
Browse files Browse the repository at this point in the history
  • Loading branch information
liyuanhe211 committed Oct 12, 2022
1 parent c82015a commit 5e9855d
Show file tree
Hide file tree
Showing 6 changed files with 178 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ Config.ini
Examples/~$4 TabColors.xlsx
/Cx_Freeze_Energy_Diagram_Plotter.py
/build/
/dist/
18 changes: 16 additions & 2 deletions Draw_Energy_Diagram_XML.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@

if platform.system() == 'Windows':
import ctypes
set_Windows_scaling_factor_env_var()
Windows_DPI_ratio, PyQt_scaling_ratio = set_Windows_scaling_factor_env_var()

del Application
Application = Qt.QApplication(sys.argv)
Expand All @@ -60,6 +60,20 @@
Application.setWindowIcon(Qt.QIcon('UI/Draw_Energy_Diagram_Icon.png'))
print('If there is a warning above starts with "libpng", ignore that.')


matplotlib_DPI_setting = 60
if platform.system() == 'Windows':
matplotlib_DPI_setting = 60/Windows_DPI_ratio
if os.path.isfile("__matplotlib_DPI_Manual_Setting.txt"):
matplotlib_DPI_manual_setting = open("__matplotlib_DPI_Manual_Setting.txt").read()
if is_int(matplotlib_DPI_manual_setting):
matplotlib_DPI_setting = matplotlib_DPI_manual_setting
matplotlib_DPI_setting = int(matplotlib_DPI_setting)



print(f"\nMatplotlib DPI: {matplotlib_DPI_setting}. \nSet an appropriate integer in __matplotlib_DPI_Manual_Setting.txt if the preview size doesn't match the output.\n")

if __name__ == '__main__':
pyqt_ui_compile('Draw_Energy_Diagram_UI_XML.py')
from UI.Draw_Energy_Diagram_UI_XML import Ui_Draw_Energy_Diagram_Form
Expand Down Expand Up @@ -558,7 +572,7 @@ def __init__(self, parent=None, y=[]):
super(MpWidget_Energy_Diagram, self).__init__()
self.setParent(parent)

self.dpi = 20
self.dpi = matplotlib_DPI_setting
self.fig = pyplot.figure(figsize=(2, 2), dpi=self.dpi, )

self.diagram_subplot = pyplot.subplot(1, 1, 1)
Expand Down
51 changes: 51 additions & 0 deletions Draw_Energy_Diagram_XML.spec
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# -*- mode: python ; coding: utf-8 -*-


block_cipher = None


a = Analysis(
['Draw_Energy_Diagram_XML.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name='Draw_Energy_Diagram_XML',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=['UI\\Draw_Energy_Diagram_Icon.ico'],
)
coll = COLLECT(
exe,
a.binaries,
a.zipfiles,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='Draw_Energy_Diagram_XML',
)
6 changes: 6 additions & 0 deletions Python_Lib/My_Lib_PyQt.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def set_Windows_scaling_factor_env_var():
DPI_ratio_for_device = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100
PyQt_scaling_ratio = QApplication.primaryScreen().devicePixelRatio()
print(f"Windows 10 High-DPI debug:",end=' ')
Windows_DPI_ratio = DPI_ratio_for_monitor if DPI_ratio_for_monitor else DPI_ratio_for_device
if DPI_ratio_for_monitor:
print("Using monitor DPI.")
ratio_of_ratio = DPI_ratio_for_monitor / PyQt_scaling_ratio
Expand All @@ -73,6 +74,11 @@ def set_Windows_scaling_factor_env_var():
print(f"Using GUI high-DPI ratio: {use_ratio}")
print("----------------------------------------------------------------------------")
os.environ["QT_SCALE_FACTOR"] = use_ratio
else:
print("Ratio of ratio near 1. Not scaling.")

return Windows_DPI_ratio,PyQt_scaling_ratio


def get_open_directories():
if not Qt.QApplication.instance():
Expand Down
Empty file.
104 changes: 104 additions & 0 deletions pyinstaller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# -*- coding: utf-8 -*-
__author__ = 'LiYuanhe'

import sys
import os
import math
import copy
import shutil
import re
import time
import random
import subprocess
from collections import OrderedDict

# import pathlib
# parent_path = str(pathlib.Path(__file__).parent.resolve())
# sys.path.insert(0,parent_path)

from Python_Lib.My_Lib_Stock import *

import PyInstaller.__main__

main_py_file = 'Draw_Energy_Diagram_XML.py'
generated_exe_name = "__Energy Diagram Plotter CDXML 3.5.exe"
icon = r"UI\Draw_Energy_Diagram_Icon.ico"
include_all_folder_contents = []
include_folders = ["UI", "Python_Lib","Examples",r"C:\Anaconda3\Lib\site-packages\setuptools"]
include_files = ["Draw_Energy_Diagram_XML.bat",
"__matplotlib_DPI_Manual_Setting.txt"]
delete_files = ["Qt5WebEngineCore.dll",
"mkl_avx512.1.dll",
"mkl_avx.1.dll",
"mkl_mc3.1.dll",
"mkl_avx2.1.dll",
"mkl_mc.1.dll",
"mkl_tbb_thread.1.dll",
"mkl_sequential.1.dll",
"mkl_vml_avx.1.dll",
"mkl_vml_mc.1.dll",
"mkl_vml_avx2.1.dll",
"mkl_vml_mc3.1.dll",
"mkl_vml_mc2.1.dll",
"mkl_vml_avx512.1.dll",
"mkl_vml_def.1.dll",
"mkl_vml_cmpt.1.dll"]


PyInstaller.__main__.run([
main_py_file,
"--icon",icon, '-y'
])


def copy_folder(src, dst):
"""
:param src:
:param dst: dst will *contain* src folder
:return:
"""
target = os.path.realpath(os.path.join(dst, filename_class(src).name))
if os.path.isdir(target):
# input('Confirm delete: '+target+" >>>")
try:
shutil.rmtree(target)
print("Deleting:", target)
except Exception:
print("Delete Failed:", target)
return None
print("Copying:", src, 'to', dst)
shutil.copytree(src, target)


generated_folder_name = os.path.join('dist',filename_class(main_py_file).name_stem)


for file in include_files:
print(f"Copying {file} to {generated_folder_name}")
shutil.copy(file,generated_folder_name)

for folder in include_folders:
copy_folder(folder, generated_folder_name)

for file in delete_files:
file = os.path.join(generated_folder_name,file)
if os.path.isfile(file):
print(f"Deleting {file}")
os.remove(file)
else:
print(f"File to remove not exist: {file}")

for folder in include_all_folder_contents:
target = os.path.realpath(os.path.join(generated_folder_name, filename_class(folder).name))
for current_object in os.listdir(folder):
current_object = os.path.join(folder, current_object)
if os.path.isfile(current_object):
shutil.copy(current_object, generated_folder_name)
else:
copy_folder(current_object, generated_folder_name)

shutil.move(os.path.join(generated_folder_name,filename_class(main_py_file).name_stem+'.exe'),
os.path.join(generated_folder_name,generated_exe_name))

open_explorer_and_select(os.path.realpath(generated_folder_name))

0 comments on commit 5e9855d

Please sign in to comment.