У меня есть этот файл, созданный на основе этого файла пользовательского интерфейса.
Я хочу его оптимизировать.
Оптимизация:
Удалить команду setObjectNames.
Удалить def retranslateUI, вместо этого установить текст об инициализации объекта. Также не используйте метод перевода. Непосредственно задайте текст без перевода.
Задайте как можно больше свойств при инициализации объекта. Например, если QLabel имеет родительский элемент, текст и выравнивание, это можно сделать в одной строке кода.
Удалить, если __name__=='__main__' : заблокировать, поскольку файл будет импортирован.
Удалите комментарии pyuic5 в начале файла.
Что еще вы думаете это оптимизирует файл.
Поскольку файл большой, я хочу автоматизировать этот процесс.Этот код:
import re
def optimize_pyuic5_file(input_file, output_file):
try:
# Read the original file
with open(input_file, 'r', encoding='utf-8') as file:
lines = file.readlines()
optimized_lines = []
in_main_block = False
setupUI_commands = []
in_setupUI = False
retranslateUI_commands = []
in_retranslateUI = False
for line in lines:
# Detect comments
if len(line.strip()) == 0:
optimized_lines.append(line)
continue
if line.strip()[0]=='#':
continue
#detect in setupUI enter
if 'def setupUi(self, MainWindow):' in line.strip():
in_setupUI = True
# detect in retranslateUI enter
if 'def retranslateUi(self, MainWindow):' in line.strip():
in_setupUI = False
in_retranslateUI = True
# remove if __name__=='__main__' block
if line.strip().startswith('from custom_qstacked_widgets import StackedWidget'):
in_retranslateUI = False
if line.strip().startswith('if __name__ == "__main__":'):
in_main_block = True
if in_setupUI:
if 'def setupUi(self, MainWindow):' not in line.strip():
setupUI_commands.append(line.strip())
elif in_retranslateUI:
if 'def retranslateUi(self, MainWindow):' not in line.strip():
retranslateUI_commands.append(line.strip())
'''
if in_main_block == False:
# remove setObjectName command
if 'setObjectName' in line.strip():
continue
else:
optimized_lines.append(line)
# Write the optimized content to the output file
with open(output_file, 'w', encoding='utf-8') as file:
file.writelines(optimized_lines)
print(f"Optimized file saved to {output_file}")
'''
output_file_contents = '''from PyQt5 import QtWidgets, QtCore, QtGui\n'''
output_file_contents += '''class Ui_MainWindow(object):\n'''
output_file_contents += '''\tdef setupUi(self, MainWindow):\n'''
output_file_contents += '''\t\tpass\n'''
output_file_contents += '''from custom_qstacked_widgets import StackedWidget\n'''
output_file_contents += '''import icons_rc\n'''
print(output_file_contents)
setupUI_commands = [setupUI_command for setupUI_command in setupUI_commands if ('setObjectName' not in setupUI_command) and ('self.retranslateUi(MainWindow)' not in setupUI_command) and ('QtCore.QMetaObject.connectSlotsByName(MainWindow)' not in setupUI_command)]
retranslateUI_commands = [retranslateUI_command for retranslateUI_command in retranslateUI_commands if ('_translate = QtCore.QCoreApplication.translate' not in retranslateUI_command)]
item_translations = []
rest_translations = []
what_to_sort = []
counter = -1
for retranslateUI_command in retranslateUI_commands:
counter += 1
if 'setSortingEnabled(__sortingEnabled)' in retranslateUI_command:
sort_object = retranslateUI_command.replace('setSortingEnabled(__sortingEnabled)', '').strip()
if sort_object.endswith('.'):
sort_object = sort_object[:-1]
what_to_sort.append(sort_object)
counter = -1
for retranslateUI_command in retranslateUI_commands:
counter += 1
if '=' in retranslateUI_command:
_equals_parts = retranslateUI_command.split('=')
left_side = _equals_parts[0].strip()
if '__sortingEnabled' not in left_side:
right_side = _equals_parts[1].strip()
setText_command = retranslateUI_commands[counter+1].strip().replace('item.','')
#remove _translate
setText_command_parts = setText_command.split('_translate(')
part_1 = setText_command_parts[0]
part_2 = setText_command_parts[1]
part_2_split = part_2.split('"')
text = part_2_split[3]
setText_command = part_1+'"'+text+'"'+')'
item_translations.append([right_side,setText_command])
counter = -1
for retranslateUI_command in retranslateUI_commands:
counter += 1
if ('.setSortingEnabled' not in retranslateUI_command) and ('__sortingEnabled =' not in retranslateUI_command) and ('item =' not in retranslateUI_command) and (retranslateUI_command.strip().startswith('item.') is False):
command_parts = retranslateUI_command.split('_translate(')
part_1 = command_parts[0][0:-1]
part_2 = command_parts[1]
text = part_2.split('"')[3]
rest_translations.append([part_1,text])
#print(what_to_sort)
#print(item_translations)
#print(rest_translations)
_text_methods = []
for item_translation in item_translations:
item_translation_part_2 = item_translation[1].split('(')[0]
if item_translation_part_2 not in _text_methods:
_text_methods.append(item_translation_part_2)
for rest_translation in rest_translations:
item_translation_part_1 = rest_translation[0].split('.')[-1].split('(')[0]
if item_translation_part_1 not in _text_methods:
_text_methods.append(item_translation_part_1)
print(_text_methods)
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
optimize_pyuic5_file('input.py', 'out-put.py')
как хорошее начало. Изменить: В retranslate_UI есть этот метод для записи текста в объект: [' setText', 'setWindowTitle', 'setStatusTip', 'setPlaceholderText', 'setTitle', 'setToolTip', 'setShortcut', 'setIconText']
У меня есть этот файл, созданный на основе этого файла пользовательского интерфейса. Я хочу его оптимизировать. Оптимизация: [list] [*]Удалить команду setObjectNames.
[*]Удалить def retranslateUI, вместо этого установить текст об инициализации объекта. Также не используйте метод перевода. Непосредственно задайте текст без перевода.
[*]Задайте как можно больше свойств при инициализации объекта. Например, если QLabel имеет родительский элемент, текст и выравнивание, это можно сделать в одной строке кода.
[*]Удалить, если __name__=='__main__' : заблокировать, поскольку файл будет импортирован.
[*]Удалите комментарии pyuic5 в начале файла. [*]Что еще вы думаете это оптимизирует файл.
[/list] Поскольку файл большой, я хочу автоматизировать этот процесс.Этот код: [code]import re
def optimize_pyuic5_file(input_file, output_file): try: # Read the original file with open(input_file, 'r', encoding='utf-8') as file: lines = file.readlines()
for line in lines: # Detect comments if len(line.strip()) == 0: optimized_lines.append(line) continue
if line.strip()[0]=='#': continue
#detect in setupUI enter if 'def setupUi(self, MainWindow):' in line.strip(): in_setupUI = True
# detect in retranslateUI enter if 'def retranslateUi(self, MainWindow):' in line.strip(): in_setupUI = False in_retranslateUI = True
# remove if __name__=='__main__' block if line.strip().startswith('from custom_qstacked_widgets import StackedWidget'): in_retranslateUI = False
if line.strip().startswith('if __name__ == "__main__":'): in_main_block = True
if in_setupUI: if 'def setupUi(self, MainWindow):' not in line.strip(): setupUI_commands.append(line.strip()) elif in_retranslateUI: if 'def retranslateUi(self, MainWindow):' not in line.strip(): retranslateUI_commands.append(line.strip())
''' if in_main_block == False: # remove setObjectName command if 'setObjectName' in line.strip(): continue else: optimized_lines.append(line)
# Write the optimized content to the output file with open(output_file, 'w', encoding='utf-8') as file: file.writelines(optimized_lines)
print(f"Optimized file saved to {output_file}") '''
setupUI_commands = [setupUI_command for setupUI_command in setupUI_commands if ('setObjectName' not in setupUI_command) and ('self.retranslateUi(MainWindow)' not in setupUI_command) and ('QtCore.QMetaObject.connectSlotsByName(MainWindow)' not in setupUI_command)] retranslateUI_commands = [retranslateUI_command for retranslateUI_command in retranslateUI_commands if ('_translate = QtCore.QCoreApplication.translate' not in retranslateUI_command)] item_translations = [] rest_translations = [] what_to_sort = [] counter = -1 for retranslateUI_command in retranslateUI_commands: counter += 1 if 'setSortingEnabled(__sortingEnabled)' in retranslateUI_command: sort_object = retranslateUI_command.replace('setSortingEnabled(__sortingEnabled)', '').strip() if sort_object.endswith('.'): sort_object = sort_object[:-1] what_to_sort.append(sort_object)
counter = -1 for retranslateUI_command in retranslateUI_commands: counter += 1 if '=' in retranslateUI_command: _equals_parts = retranslateUI_command.split('=') left_side = _equals_parts[0].strip() if '__sortingEnabled' not in left_side: right_side = _equals_parts[1].strip() setText_command = retranslateUI_commands[counter+1].strip().replace('item.','') #remove _translate setText_command_parts = setText_command.split('_translate(') part_1 = setText_command_parts[0] part_2 = setText_command_parts[1] part_2_split = part_2.split('"') text = part_2_split[3] setText_command = part_1+'"'+text+'"'+')' item_translations.append([right_side,setText_command])
counter = -1 for retranslateUI_command in retranslateUI_commands: counter += 1 if ('.setSortingEnabled' not in retranslateUI_command) and ('__sortingEnabled =' not in retranslateUI_command) and ('item =' not in retranslateUI_command) and (retranslateUI_command.strip().startswith('item.') is False): command_parts = retranslateUI_command.split('_translate(') part_1 = command_parts[0][0:-1] part_2 = command_parts[1] text = part_2.split('"')[3] rest_translations.append([part_1,text])
_text_methods = [] for item_translation in item_translations: item_translation_part_2 = item_translation[1].split('(')[0] if item_translation_part_2 not in _text_methods: _text_methods.append(item_translation_part_2)
for rest_translation in rest_translations: item_translation_part_1 = rest_translation[0].split('.')[-1].split('(')[0] if item_translation_part_1 not in _text_methods: _text_methods.append(item_translation_part_1)
print(_text_methods)
except Exception as e: print(f"An error occurred: {e}")
if __name__ == "__main__": optimize_pyuic5_file('input.py', 'out-put.py') [/code] как хорошее начало. [b]Изменить:[/b] В retranslate_UI есть этот метод для записи текста в объект: [' setText', 'setWindowTitle', 'setStatusTip', 'setPlaceholderText', 'setTitle', 'setToolTip', 'setShortcut', 'setIconText']