【PyQt5】{16} —— QTextEdit文本编辑框(制作一个简易的记事本)

QTextEdit

QTextEdit类提供了一个部件,用于编辑和显示纯文本和富文本。


QTextEdit的一些方法和属性:

  • toPlainText():获取文本
  • setText():设置文本
  • textChanged:文本改变信号(在文本每次发生改变时发射)
  • clear():清空文本
  • setPlaceholderText():设置占位字符串(只有在文本编辑框中没有任何文本时才会显示)

一个简易的记事本:

# -*- coding: utf-8 -*-
"""
Created on Sat May  9 16:17:57 2020

@author: Giyn
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QTextEdit, QVBoxLayout, QHBoxLayout, QMessageBox
from PyQt5.QtGui import QIcon


class Simple_Window(QWidget):
    def __init__(self):
        super(Simple_Window, self).__init__() # 使用super函数可以实现子类使用父类的方法
        self.setWindowTitle("记事本")
        self.setWindowIcon(QIcon('NoteBook.png')) # 设置窗口图标
        self.resize(412, 412)
        self.text_edit = QTextEdit(self) # 实例化一个QTextEdit对象
        self.text_edit.setText("Hello World") # 设置编辑框初始化时显示的文本
        self.text_edit.setPlaceholderText("Please edit text here") # 设置占位字符串
        self.text_edit.textChanged.connect(lambda: print("text is changed!")) # 判断文本是否发生改变
        
        self.save_button = QPushButton("Save", self)
        self.clear_button = QPushButton("Clear", self)
        
        self.save_button.clicked.connect(lambda: self.button_slot(self.save_button))
        self.clear_button.clicked.connect(lambda: self.button_slot(self.clear_button))
        
        self.h_layout = QHBoxLayout()
        self.v_layout = QVBoxLayout()
        
        self.h_layout.addWidget(self.save_button)
        self.h_layout.addWidget(self.clear_button)
        self.v_layout.addWidget(self.text_edit)
        self.v_layout.addLayout(self.h_layout)
        
        self.setLayout(self.v_layout)

    def button_slot(self, button):
        if button == self.save_button:
            choice = QMessageBox.question(self, "Question", "Do you want to save it?", QMessageBox.Yes | QMessageBox.No)
            if choice == QMessageBox.Yes:
                with open('First text.txt', 'w') as f:
                    f.write(self.text_edit.toPlainText())
                self.close()
            elif choice == QMessageBox.No:
                self.close()
        elif button == self.clear_button:
            self.text_edit.clear()
        
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Simple_Window()
    window.show()
    sys.exit(app.exec())

Output:


When clicking the “Clear”:

>>> text is changed!

When changing the text:

>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!
>>> text is changed!

When clicking the “Save”:

After clicking “Yes”:

在这里插入图片描述
Then the program close.


If clicking “No”, the program will close directly.


Reference:https://study.163.com/course/courseLearn.htm?courseId=1208995818

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章