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