这是我在网上找的代码(找不到出处了,抱歉)
本来是不能随窗口缩放的,但是我修改了所有布局继承centralwidget,就可以随窗口缩放了
mainUi.py# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
# MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
# self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setContentsMargins(1, 1, 1, 0)
# self.verticalLayout.setObjectName("verticalLayout")
self.txt_view = QtWidgets.QTextEdit(self.centralwidget)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(8)
self.txt_view.setFont(font)
# self.txt_view.setObjectName("txt_view")
self.verticalLayout.addWidget(self.txt_view)
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 7)
# self.horizontalLayout.setObjectName("horizontalLayout")
self.btn_open = QtWidgets.QPushButton(self.centralwidget)
# self.btn_open.setObjectName("btn_open")
self.horizontalLayout.addWidget(self.btn_open)
self.btn_save = QtWidgets.QPushButton(self.centralwidget)
# self.btn_save.setObjectName("btn_save")
self.horizontalLayout.addWidget(self.btn_save)
self.verticalLayout.addLayout(self.horizontalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "文本编辑"))
self.btn_open.setText(_translate("MainWindow", "打开文件"))
self.btn_save.setText(_translate("MainWindow", "保存文件"))
main.py# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
import mainUi
class MainCode(QMainWindow, mainUi.Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
mainUi.Ui_MainWindow.__init__(self)
self.setupUi(self)
self.btn_save.clicked.connect(self.on_save)
self.btn_open.clicked.connect(self.on_open)
def on_save(self):
FullFileName, _ = QFileDialog.getSaveFileName(
self, "文件另存为", r"./", "TXT (*.txt)"
)
if FullFileName == "":
return
set_text = self.txt_view.toPlainText()
with open(FullFileName, "wt", encoding="utf-8") as f:
f.write(set_text)
f.close()
def on_open(self):
FullFileName, a = QFileDialog.getOpenFileName(
self, "打开文件", r"./", "TXT (*.txt)"
)
if FullFileName == "":
return
with open(FullFileName, "rt", encoding="utf-8") as f:
txtstr = f.read()
self.txt_view.setText(txtstr)
f.close()
if __name__ == "__main__":
from sys import argv, exit
app = QApplication(argv)
md = MainCode()
md.show()
exit(app.exec())
运行main.py
具体原理我也不咋懂,应该可以启发一下
|