PyQt5 Demo 記事本(實現大部分功能)

實現了大部分記事本的功能,替換功能未能實現,還有主題樣式、狀態欄等,今後再加吧!

學習總結一,直接上代碼~


Demo 記事本

登錄主窗口(.ui轉爲.py):untitled.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'I:\1實驗室\其他\QTtest\untitled.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(399, 322)
        self.label_state = QtWidgets.QLabel(Dialog)
        self.label_state.setGeometry(QtCore.QRect(20, 290, 191, 16))
        self.label_state.setObjectName("label_state")
        self.btn_ok = QtWidgets.QPushButton(Dialog)
        self.btn_ok.setGeometry(QtCore.QRect(80, 230, 75, 23))
        self.btn_ok.setObjectName("btn_ok")
        self.btn_cancel = QtWidgets.QPushButton(Dialog)
        self.btn_cancel.setGeometry(QtCore.QRect(230, 230, 75, 23))
        self.btn_cancel.setObjectName("btn_cancel")
        self.lineEdit_username = QtWidgets.QLineEdit(Dialog)
        self.lineEdit_username.setGeometry(QtCore.QRect(150, 50, 171, 20))
        self.lineEdit_username.setObjectName("lineEdit_username")
        self.label_username = QtWidgets.QLabel(Dialog)
        self.label_username.setGeometry(QtCore.QRect(50, 50, 61, 16))
        self.label_username.setObjectName("label_username")
        self.lineEdit_password = QtWidgets.QLineEdit(Dialog)
        self.lineEdit_password.setGeometry(QtCore.QRect(150, 90, 171, 20))
        self.lineEdit_password.setInputMethodHints(QtCore.Qt.ImhNoAutoUppercase|QtCore.Qt.ImhNoPredictiveText|QtCore.Qt.ImhSensitiveData)
        self.lineEdit_password.setEchoMode(QtWidgets.QLineEdit.PasswordEchoOnEdit)
        self.lineEdit_password.setObjectName("lineEdit_password")
        self.label_password = QtWidgets.QLabel(Dialog)
        self.label_password.setGeometry(QtCore.QRect(50, 90, 61, 16))
        self.label_password.setObjectName("label_password")

        self.retranslateUi(Dialog)
        self.btn_cancel.clicked.connect(Dialog.close)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label_state.setText(_translate("Dialog", "TextLabel"))
        self.btn_ok.setText(_translate("Dialog", "ok"))
        self.btn_cancel.setText(_translate("Dialog", "cancel"))
        self.label_username.setText(_translate("Dialog", "User name"))
        self.label_password.setText(_translate("Dialog", "Password"))

登錄成功提示窗口(.ui轉爲.py):information_ok.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'I:\1實驗室\其他\QTtest\information_ok.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(208, 122)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(10, 10, 181, 71))
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.buttonBox = QtWidgets.QDialogButtonBox(Form)
        self.buttonBox.setGeometry(QtCore.QRect(0, 70, 171, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")

        self.retranslateUi(Form)
        self.buttonBox.clicked['QAbstractButton*'].connect(Form.close)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "登錄成功!"))

登錄失敗提示窗口(.ui轉爲.py):information_no.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'I:\1實驗室\其他\QTtest\information_no.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(208, 122)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(10, 10, 181, 71))
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.buttonBox = QtWidgets.QDialogButtonBox(Form)
        self.buttonBox.setGeometry(QtCore.QRect(0, 70, 171, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")

        self.retranslateUi(Form)
        self.buttonBox.clicked['QAbstractButton*'].connect(Form.close)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "登錄失敗!"))

記事本界面(.ui轉爲.py):mainMenu.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'I:\1實驗室\其他\QTtest\mainMenu.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainMenu(object):
    def setupUi(self, MainMenu):
        MainMenu.setObjectName("MainMenu")
        MainMenu.resize(800, 663)
        self.centralwidget = QtWidgets.QWidget(MainMenu)
        self.centralwidget.setObjectName("centralwidget")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(30, 110, 731, 451))
        self.textEdit.setObjectName("textEdit")
        self.btn_ok = QtWidgets.QPushButton(self.centralwidget)
        self.btn_ok.setGeometry(QtCore.QRect(590, 580, 75, 23))
        self.btn_ok.setObjectName("btn_ok")
        self.btn_cancel = QtWidgets.QPushButton(self.centralwidget)
        self.btn_cancel.setGeometry(QtCore.QRect(680, 580, 75, 23))
        self.btn_cancel.setObjectName("btn_cancel")
        self.label_state = QtWidgets.QLabel(self.centralwidget)
        self.label_state.setGeometry(QtCore.QRect(30, 580, 191, 16))
        self.label_state.setObjectName("label_state")
        self.label_path = QtWidgets.QLabel(self.centralwidget)
        self.label_path.setGeometry(QtCore.QRect(40, 70, 51, 20))
        self.label_path.setAlignment(QtCore.Qt.AlignCenter)
        self.label_path.setObjectName("label_path")
        self.lineEdit_path = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_path.setGeometry(QtCore.QRect(110, 69, 551, 31))
        self.lineEdit_path.setObjectName("lineEdit_path")
        self.btn_browser = QtWidgets.QPushButton(self.centralwidget)
        self.btn_browser.setGeometry(QtCore.QRect(680, 70, 75, 23))
        self.btn_browser.setObjectName("btn_browser")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(0, 0, 801, 41))
        self.groupBox.setTitle("")
        self.groupBox.setObjectName("groupBox")
        self.fontComboBox = QtWidgets.QFontComboBox(self.groupBox)
        self.fontComboBox.setGeometry(QtCore.QRect(20, 10, 171, 22))
        self.fontComboBox.setObjectName("fontComboBox")
        self.btn_setting = QtWidgets.QPushButton(self.groupBox)
        self.btn_setting.setGeometry(QtCore.QRect(200, 10, 61, 23))
        self.btn_setting.setObjectName("btn_setting")
        MainMenu.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainMenu)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuEdit = QtWidgets.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")
        self.menuHelp = QtWidgets.QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        self.menuOthers = QtWidgets.QMenu(self.menubar)
        self.menuOthers.setObjectName("menuOthers")
        MainMenu.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainMenu)
        self.statusbar.setObjectName("statusbar")
        MainMenu.setStatusBar(self.statusbar)
        self.actionOpen = QtWidgets.QAction(MainMenu)
        self.actionOpen.setObjectName("actionOpen")
        self.actionSave = QtWidgets.QAction(MainMenu)
        self.actionSave.setObjectName("actionSave")
        self.actionExit = QtWidgets.QAction(MainMenu)
        self.actionExit.setObjectName("actionExit")
        self.actionRestart = QtWidgets.QAction(MainMenu)
        self.actionRestart.setObjectName("actionRestart")
        self.actionAbout_us = QtWidgets.QAction(MainMenu)
        self.actionAbout_us.setObjectName("actionAbout_us")
        self.actionCopy = QtWidgets.QAction(MainMenu)
        self.actionCopy.setObjectName("actionCopy")
        self.actionPaste = QtWidgets.QAction(MainMenu)
        self.actionPaste.setObjectName("actionPaste")
        self.actionCut = QtWidgets.QAction(MainMenu)
        self.actionCut.setObjectName("actionCut")
        self.actionSelect_all = QtWidgets.QAction(MainMenu)
        self.actionSelect_all.setObjectName("actionSelect_all")
        self.actionClear_all = QtWidgets.QAction(MainMenu)
        self.actionClear_all.setObjectName("actionClear_all")
        self.actionAdd_date = QtWidgets.QAction(MainMenu)
        self.actionAdd_date.setObjectName("actionAdd_date")
        self.actionFont = QtWidgets.QAction(MainMenu)
        self.actionFont.setObjectName("actionFont")
        self.actionFind = QtWidgets.QAction(MainMenu)
        self.actionFind.setObjectName("actionFind")
        self.actionReplace = QtWidgets.QAction(MainMenu)
        self.actionReplace.setObjectName("actionReplace")
        self.actionUndo = QtWidgets.QAction(MainMenu)
        self.actionUndo.setObjectName("actionUndo")
        self.actionPrint = QtWidgets.QAction(MainMenu)
        self.actionPrint.setObjectName("actionPrint")
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addAction(self.actionSave)
        self.menuFile.addAction(self.actionExit)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionRestart)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionPrint)
        self.menuEdit.addAction(self.actionCopy)
        self.menuEdit.addAction(self.actionPaste)
        self.menuEdit.addAction(self.actionCut)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionSelect_all)
        self.menuEdit.addAction(self.actionClear_all)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionAdd_date)
        self.menuEdit.addSeparator()
        self.menuEdit.addAction(self.actionFont)
        self.menuHelp.addAction(self.actionAbout_us)
        self.menuOthers.addAction(self.actionFind)
        self.menuOthers.addAction(self.actionReplace)
        self.menuOthers.addAction(self.actionUndo)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.menubar.addAction(self.menuOthers.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

        self.retranslateUi(MainMenu)
        self.btn_cancel.clicked.connect(MainMenu.close)
        QtCore.QMetaObject.connectSlotsByName(MainMenu)

    def retranslateUi(self, MainMenu):
        _translate = QtCore.QCoreApplication.translate
        MainMenu.setWindowTitle(_translate("MainMenu", "MainMenu"))
        self.btn_ok.setText(_translate("MainMenu", "Ok"))
        self.btn_cancel.setText(_translate("MainMenu", "Cancel"))
        self.label_state.setText(_translate("MainMenu", "State:"))
        self.label_path.setText(_translate("MainMenu", "Path"))
        self.btn_browser.setText(_translate("MainMenu", "Browser"))
        self.btn_setting.setText(_translate("MainMenu", "Setting"))
        self.menuFile.setTitle(_translate("MainMenu", "File"))
        self.menuEdit.setTitle(_translate("MainMenu", "Edit"))
        self.menuHelp.setTitle(_translate("MainMenu", "Help"))
        self.menuOthers.setTitle(_translate("MainMenu", "Others"))
        self.actionOpen.setText(_translate("MainMenu", "Open"))
        self.actionOpen.setShortcut(_translate("MainMenu", "Ctrl+O"))
        self.actionSave.setText(_translate("MainMenu", "Save"))
        self.actionSave.setShortcut(_translate("MainMenu", "Ctrl+S"))
        self.actionExit.setText(_translate("MainMenu", "Exit"))
        self.actionExit.setShortcut(_translate("MainMenu", "Ctrl+D"))
        self.actionRestart.setText(_translate("MainMenu", "Restart"))
        self.actionAbout_us.setText(_translate("MainMenu", "About us"))
        self.actionCopy.setText(_translate("MainMenu", "Copy"))
        self.actionCopy.setShortcut(_translate("MainMenu", "Ctrl+C"))
        self.actionPaste.setText(_translate("MainMenu", "Paste"))
        self.actionPaste.setShortcut(_translate("MainMenu", "Ctrl+V"))
        self.actionCut.setText(_translate("MainMenu", "Cut"))
        self.actionCut.setShortcut(_translate("MainMenu", "Ctrl+X"))
        self.actionSelect_all.setText(_translate("MainMenu", "Select all"))
        self.actionSelect_all.setShortcut(_translate("MainMenu", "Ctrl+A"))
        self.actionClear_all.setText(_translate("MainMenu", "Clear all"))
        self.actionAdd_date.setText(_translate("MainMenu", "Add date"))
        self.actionFont.setText(_translate("MainMenu", "Font"))
        self.actionFind.setText(_translate("MainMenu", "Find"))
        self.actionFind.setShortcut(_translate("MainMenu", "Ctrl+F"))
        self.actionReplace.setText(_translate("MainMenu", "Replace"))
        self.actionReplace.setShortcut(_translate("MainMenu", "Ctrl+R"))
        self.actionUndo.setText(_translate("MainMenu", "Undo"))
        self.actionUndo.setShortcut(_translate("MainMenu", "Ctrl+Z"))
        self.actionPrint.setText(_translate("MainMenu", "Print"))
        self.actionPrint.setShortcut(_translate("MainMenu", "Ctrl+P"))

進度條(.ui轉爲.py):progressbar.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'I:\1實驗室\其他\QTtest\progressbar.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 66)
        Form.setWindowOpacity(0.5)
        Form.setAutoFillBackground(False)
        self.progressBar = QtWidgets.QProgressBar(Form)
        self.progressBar.setGeometry(QtCore.QRect(40, 20, 331, 23))
        self.progressBar.setProperty("value", 24)
        self.progressBar.setObjectName("progressBar")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))

主函數:run.py

# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 00:53:14 2020

@author: Administrator
"""

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QTimer, QDateTime, QBasicTimer
from PyQt5.QtGui import QIcon, QTextDocument
from PyQt5.QtPrintSupport import QPrinter, QPrintDialog,QPrintPreviewDialog

from untitled import Ui_Dialog
from information_ok import Ui_Form as form_ok
from information_no import Ui_Form as form_no
from mainMenu import Ui_MainMenu
from progressbar import Ui_Form

class mywindow(QtWidgets.QDialog, Ui_Dialog):
    def  __init__ (self):
        super(mywindow, self).__init__()
        self.setupUi(self)
        self.btn_ok.clicked.connect(self.printState)
        
    def printState(self):
        #顯示狀態
#        if self.lineEdit_username.text == "1" and self.lineEdit_password.text == "1":
        if self.lineEdit_username.text().strip() == "1" and self.lineEdit_password.text() == "1":
            words = "Login successful!"
            self.w1 = window_ok()
            self.w1.show()
            self.close()
                        
        else:
            words = "Login faild!"
            self.w2 = window_no()
            self.w2.show()
            self.close()
        self.label_state.setText(words)

class window_ok(QtWidgets.QWidget, form_ok):
    def  __init__ (self):
        super(window_ok, self).__init__()
        self.setupUi(self)
        self.buttonBox.clicked.connect(self.showMenu)
        
    def showMenu(self):
        #顯示菜單
        self.m = menu()
        self.m.show()
        self.close()
        
class window_no(QtWidgets.QWidget, form_no):
    def  __init__ (self):
        super(window_no, self).__init__()
        self.setupUi(self)
        self.buttonBox.clicked.connect(self.showLogin)
        
    def showLogin(self):
        self.l = mywindow()
        self.l.show()
        self.close()
        
class menu(QtWidgets.QMainWindow, Ui_MainMenu):
    def __init__(self):
        super(menu, self).__init__()
        self.setupUi(self)
        self.btn_ok.clicked.connect(self.printState)
        self.btn_browser.clicked.connect(self.browser)
        self.actionOpen.triggered.connect(self.browser) #menu/open
        self.actionSave.triggered.connect(self.printState) #menu/save
        self.actionExit.triggered.connect(self.menu_Exit) #menu/exit
        self.actionRestart.triggered.connect(self.menu_Restart) #menu/restart
        self.actionPrint.triggered.connect(self.menu_print)#menu/print
        self.actionCopy.triggered.connect(self.menu_Copy) #menu/copy
        self.actionPaste.triggered.connect(self.menu_Paste) #menu/paste
        self.actionCut.triggered.connect(self.menu_Cut) #menu/cut
        self.actionSelect_all.triggered.connect(self.menu_selectAll) #menu/Select_all
        self.actionClear_all.triggered.connect(self.menu_clearAll) #menu/Clear_all
        self.actionAdd_date.triggered.connect(self.menu_addDate) #menu/Add_date
        self.actionFont.triggered.connect(self.menu_font) #menu/font
        self.actionFind.triggered.connect(self.menu_find) #menu/find
#        self.actionReplace.triggered.connect(self.menu_replace) #menu/replace
        self.actionUndo.triggered.connect(self.menu_undo) #menu/undo
        self.actionAbout_us.triggered.connect(self.menu_aboutUs) #menu/About_us
        
        self.fontComboBox.currentFontChanged.connect(self.tool_font) #工具欄的字體設置
        self.btn_setting.clicked.connect(self.menu_font) #工具欄的Setting按鈕
        
    #保存並打印狀態    
    def printState(self):
        
        #保存txt
        save_path = QtWidgets.QFileDialog.getSaveFileName(self, "存儲", "I:\\1實驗室\\其他\\QTtest\\", "Text Files (*.txt);;All Files (*)")
        #設置文件擴展名過濾,注意用雙分號間隔
        f = open(save_path[0], "w", encoding="utf-8")
        my_data = self.textEdit.toPlainText()
        f.write(my_data)
        f.close()
        #顯示進度條
        progressBar().show()
        #打印狀態
        words = "Save successful!"
        self.label_state.setText(words)
            
    #文件目錄瀏覽並顯示路徑及內容
    def browser(self):
#        onload_path = QtWidgets.QFileDialog.getExistingDirectory(self, "瀏覽", "I:\\1實驗室\\其他\\QTtest\\")
        onload_path = QtWidgets.QFileDialog.getOpenFileName(self, "瀏覽", "I:\\1實驗室\\其他\\QTtest\\", "Text Files (*.txt);;All Files (*)")
        #設置文件擴展名過濾,用雙分號間隔
#        print(onload_path)
        self.lineEdit_path.setText(onload_path[0])  
        #顯示文件的內容
#        f = open(onload_path[0], "r", encoding="ISO-8859-1")
        f = open(onload_path[0], "r", encoding="utf-8")
        my_data = f.read()
        f.close()
        self.textEdit.setText(my_data)
        
    #退出此窗口
    def menu_Exit(self):
        self.close()
        
    #重啓窗口
    def menu_Restart(self):
        self.hide()
        self.textEdit.setText("")
        self.lineEdit_path.setText("")
        import time
        time.sleep(1) #時間延遲1s
        self.show()
       
    #複製內容
    def menu_Copy(self):
        self.textEdit.copy()
    
    #粘貼內容
    def menu_Paste(self):
        self.textEdit.paste()
      
    #剪切內容
    def menu_Cut(self):
        self.textEdit.cut()

    #全選內容
    def menu_selectAll(self):
        self.textEdit.selectAll()
        
    #清空內容
    def menu_clearAll(self):
        self.textEdit.clear()
        
    #添加日期
    def menu_addDate(self):
        time = QDateTime.currentDateTime()
        timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd")
        self.textEdit.append(timeDisplay)
        
    #關於我們
    def menu_aboutUs(self):
        QMessageBox.information(self,"關於我們","This is a demo!", QMessageBox.Ok | QMessageBox.Close, QMessageBox.Close)

    #字體設置-菜單的font
    def menu_font(self):
        font_dialog = QtWidgets.QFontDialog()
        font_dialog.show()
        font, isok = font_dialog.getFont()
        print("font: "+str(font))
        if isok == True:
            self.textEdit.setFont(font)
            self.fontComboBox.setCurrentFont(font)
    
    #字體設置-工具欄的font
    def tool_font(self):
        font = self.fontComboBox.currentFont()
        self.textEdit.setFont(font)
        
    #撤銷
    def menu_undo(self):
        self.textEdit.undo()
        
    #查找
    def menu_find(self):
        findDlg = QtWidgets.QDialog(self)
        findDlg.setWindowTitle('查找...')

        self.find_textLineEdit = QtWidgets.QLineEdit(findDlg)
        find_next_button = QtWidgets.QPushButton('查找下一個', findDlg)
        find_last_button = QtWidgets.QPushButton('查找上一個', findDlg)

        v_layout = QtWidgets.QVBoxLayout(self)
        v_layout.addWidget(find_last_button)
        v_layout.addWidget(find_next_button)

        h_layout = QtWidgets.QHBoxLayout(findDlg)
        h_layout.addWidget(self.find_textLineEdit)
        h_layout.addLayout(v_layout)

        find_last_button.clicked.connect(self.show_findLast)
        find_next_button.clicked.connect(self.show_findNext)

        findDlg.show()

    def show_findLast(self):
        find_text = self.find_textLineEdit.text()
        print(find_text)
        print(self.textEdit.find(find_text, QTextDocument.FindBackward))
        # if self.textEdit.find(find_text, QTextDocument.find):
        #     QMessageBox.warning(self, '查找', '找不到 {}'.format(find_text))

    def show_findNext(self):
        find_text = self.find_textLineEdit.text()
        print(find_text)
        print(self.textEdit.find(find_text, QTextDocument.FindBackward))
        if self.textEdit.find(find_text, QTextDocument.FindBackward):
            QMessageBox.warning(self, '查找', '找不到 {}'.format(find_text))

    #替換(基於查找功能添加按鈕及替換操作)
#    def menu_replace(self):
#        findDlg = QtWidgets.QDialog(self)
#        findDlg.setWindowTitle('替換...')

    #打印
    def menu_print(self):
        dialog = QPrintPreviewDialog()
        dialog.paintRequested.connect(self.handlePrint)
        dialog.exec_()
    
    def handlePrint(self, printer):#打印方法
        self.textEdit.print(printer)

#進度條
class progressBar(QtWidgets.QWidget, Ui_Form):
    def  __init__ (self):
        super(progressBar, self).__init__()
        self.setupUi(self)
#        self.buttonBox.clicked.connect(self.showLogin)
#        self.show()
        self.timer = QBasicTimer()
        self.step = 0
        
    def timerEvent(self, event):
        if self.step >=100:
            self.timer.stop()
            return
        self.step = self.step + 1
        self.progressBar.setValue(self.step)
        import time
        time.sleep(1)
        
        

if __name__=="__main__":
    import sys
    # 添加if判斷語句可以解決spyder內核重啓的問題
    if not QtWidgets.QApplication.instance():
        app = QtWidgets.QApplication(sys.argv)
    else:
        app = QtWidgets.QApplication.instance()
#    app=QtWidgets.QApplication(sys.argv)
    ui = mywindow()    
    ui.show()
#    input("input something")
    sys.exit(app.exec_())

運行界面

登錄界面見上一篇博客,下面主要展示記事本功能。

  

注意事項

  1. 之前的問題:運行時總會出現“Kernel died, restarting”,今天得以解決。
    app=QtWidgets.QApplication(sys.argv)

    替換爲:

        # 添加if判斷語句可以解決spyder內核重啓的問題
        if not QtWidgets.QApplication.instance():
            app = QtWidgets.QApplication(sys.argv)
        else:
            app = QtWidgets.QApplication.instance()
    

    原因爲:實例化QApplication是造成內核重啓的根源,因爲ipython console在同一進程中只允許一個QApplication存在,否則就會出現內核分割錯誤,所以我們在實例化QApplication之前應該加入判斷語句。
    (引用自:https://blog.csdn.net/MSDN_tang/article/details/80098412) 

  2. .txt文件讀取過程中,編碼方式需要注意。
    有大佬說,ISO-8859-1基本能處理常見問題,但親測還是有問題,能夠讀取文件內容,但中文顯示是亂碼。
    有很多關於這個的教程,但親測最方便、簡單、暴力的方法是:將需要讀取的.txt文件另存爲utf-8格式,然後再以utf-8格式進行讀取操作。

  3.  保存文件獲取的路徑save_path,在使用open方法時,應使用save_path[0]。
    且文件擴展名過濾應該使用雙分號間隔。

            #保存txt
            save_path = QtWidgets.QFileDialog.getSaveFileName(self, "存儲", "I:\\1實驗室\\其他\\QTtest\\", "Text Files (*.txt);;All Files (*)")
            #設置文件擴展名過濾,注意用雙分號間隔
            f = open(save_path[0], "w", encoding="utf-8")

     

  4. 設置字體時,應特別注意控件所對應的方法及個人所需要實現的功能是不同的,如textEdit與fontComboBox。
    fontComboBox同樣也有setFont()方法,但使用之後會發現,改變的是控件內的字體,而非我想要實現的內容。

        #字體設置-菜單的font
        def menu_font(self):
            font_dialog = QtWidgets.QFontDialog()
            font_dialog.show()
            font, isok = font_dialog.getFont()
            print("font: "+str(font))
            if isok == True:
                self.textEdit.setFont(font)
                self.fontComboBox.setCurrentFont(font)

     

  5. 此記事本所實現的功能包括:文本編輯、保存、打開、替換、撤銷、打印及打印預覽、退出、重啓、複製、粘貼、剪切、選擇全部、清空、撤銷、進度條、添加日期、關於我們等功能。

  6. 其中替換、打印及打印預覽、進度條等功能主要參考了其他大佬的作品,小菜在此表示感謝,參考鏈接爲:

    https://blog.csdn.net/BigTail_cat/article/details/80611993

    https://blog.csdn.net/qq_43071318/article/details/102869617

    https://blog.csdn.net/c3060911030/article/details/51552325

     

存在的問題

  1. 很遺憾,替換功能未能實現,主要是卡在不知道如何將選中的內容替換爲新的內容,待小菜詳細閱讀開發文檔之後再行補充。
  2. 控件及窗體略醜,待今後改進。在查閱資料的時候,看到這位大佬的博客內容棒棒噠,是關於QSS美化主題的,在此分享給大家:
    https://www.cnblogs.com/yywBlogW/p/11617956.html

有緣看到的小夥伴,給人家點個讚唄~麼麼噠❤

 

 

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