使用 Qt Designer 設計後,是個 .ui 格式,要再轉成 python 語法:
pyisde6-uic main.ui -o main.py
開始主程式,from main import Ui_MainWindow ,就可以出現畫面了。
from PySide6.QtCore import *
from PySide6.QtWidgets import *
from main import Ui_MainWindow
import sys
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# 加入各互動事件程序
self.btn_selectFiles.clicked.connect(self.select_files)
def select_files(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
files, _ = QFileDialog.getOpenFileNames(self, 'Select files', '', 'All Files (*);;Text Files (*.txt)', options=options)
if files:
print('Selected files:', files)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
在上述的 main.py 的中文字是編碼過的不好看,如果很介意,可以再以下方程式做轉碼成原中文。
指令例:python tran_ui.py -i main.py -o main_new.py
import argparse
def convert_unicode(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
converted_content = content.encode('utf-8').decode('unicode-escape').encode('utf-8')
with open(output_file, 'w', encoding='utf-8') as f:
f.write(converted_content.decode('utf-8'))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Convert unicode in input file to utf-8 in output file')
parser.add_argument('-i', '--input', type=str, required=True, help='Path to input file')
parser.add_argument('-o', '--output', type=str, required=True, help='Path to output file')
args = parser.parse_args()
convert_unicode(args.input, args.output)