[PYTHON] I tried to make a simple text editor using PyQt

I made a simple text editor using PyQt.

Simpletextedit.py



# -*- coding:utf-8 -*-
# Very Simple Text Editor

# Initial setting & import library
import sys, codecs
from PyQt4 import QtGui, QtCore, QtWebKit
app = QtGui.QApplication(sys.argv)


# Main Window
class CustomMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(CustomMainWindow, self).__init__(parent)

	# Set Window Style
        self.resize(800, 500)
        self.setWindowTitle("SimpleTextEditor")
        self.setStyleSheet("background-color: white")
	# Enable file drop
        self.setAcceptDrops(True)
	# Add text editer
        self.addtextedit()


        # Tool Bar
        self.file_tool = self.addToolBar("File")
        self.edit_tool = self.addToolBar("Exit")

        newbutton = self.file_tool.addAction("New...")
	self.connect(newbutton, QtCore.SIGNAL('triggered()'), self.addtextedit)

        openbutton = self.file_tool.addAction("Open...")
	self.connect(openbutton, QtCore.SIGNAL('triggered()'), self.showFileDialog)

        closebutton = self.edit_tool.addAction("Save...")
	self.connect(closebutton, QtCore.SIGNAL('triggered()'), self.saveFile)

        closebutton = self.edit_tool.addAction("Close...")
	self.connect(closebutton, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))

        # Add MenuBar
        filemenu = self.menuBar()
        filemenu = filemenu.addMenu('&File')
	filemenu.addMenu("New...")
        filemenu.addMenu("Open...")
        filemenu.addMenu("Save...")

	# Add Open menu
        a = QtGui.QAction('Open', self)
        a.setShortcut('Ctrl+o')
        self.connect(a, QtCore.SIGNAL('triggered()'),
                     self.showFileDialog)
        filemenu.addAction(a)
        
        # Add Exit menu
        a = QtGui.QAction('Exit', self)
        a.setShortcut('Ctrl+w')
        self.connect(a, QtCore.SIGNAL('triggered()'),
                     QtCore.SLOT('close()'))
        filemenu.addAction(a)

	# Add Save menu
        a = QtGui.QAction('Save', self)
        a.setShortcut('Ctrl+s')
        self.connect(a, QtCore.SIGNAL('triggered()'),
                     self.saveFile)
        filemenu.addAction(a)

    # Setting Dialog
    def showFileDialog(self):
        # Add text Editer
        self.textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.textEdit)

        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open', '.')
        f = open(unicode(fname))
        self.textEdit.setText(f.read())

    # Accept drag of file
    def dragEnterEvent(self, e):
        print("c")
        if e.mimeData().hasUrls():
            e.accept()
        else:
            e.ignore()

    # Drop processing
    def dropEvent(self, e):

        # Add text Editer
        self.textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.textEdit)

	# Open drop files
        for u in e.mimeData().urls():
            p = unicode(u.toLocalFile())
	    print ("Open file at " + p)
            f = open(unicode(p))
            self.textEdit.setText(f.read())

    # add save file dialog
    def saveFile(self):
        savename = unicode(QtGui.QFileDialog.getSaveFileName(self, 'Save file', ''))
        fname = codecs.open(savename,'w','utf-8')
	fname.write(self.textEdit.toPlainText())

    # add Central Widget => textedit
    def addtextedit(self):
	# Add text Editer
        self.textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.textEdit)

# Create instance
def main():
    main = CustomMainWindow()
    main.show()
    app.exec_()

if __name__ == '__main__':
    main()

Recommended Posts

I tried to make a simple text editor using PyQt
I tried to make a ○ ✕ game using TensorFlow
I tried to make a stopwatch using tkinter in python
I tried using Azure Speech to Text.
I tried to classify text using TensorFlow
I tried to make a Web API
I tried to make a regular expression of "time" using Python
I tried to make a regular expression of "date" using Python
[Python] I tried to make a simple program that works on the command line using argparse.
I tried to make a "fucking big literary converter"
I tried to draw a configuration diagram using Diagrams
I tried to make a simple mail sending application with tkinter of Python
I tried to make a suspicious person MAP quickly using Geolonia address data
I tried to make a simple image recognition API with Fast API and Tensorflow
I tried Watson Speech to Text
I tried to automate [a certain task] using Raspberry Pi
[Git] I tried to make it easier to understand how to use git stash using a concrete example
I tried to make a document search slack command using Kendra announced at re: Invent 2019.
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
I tried to get a database of horse racing using Pandas
I tried to create a simple credit score by logistic regression.
I tried to make a system that fetches only deleted tweets
[Python] I tried to implement stable sorting, so make a note
I tried to implement anomaly detection using a hidden Markov model
[3rd] I tried to make a certain authenticator-like tool with python
I tried to make a periodical process with Selenium and Python
I tried to get a list of AMI Names using Boto3
I tried to make a 2channel post notification application with Python
[4th] I tried to make a certain authenticator-like tool with python
[Python] Simple Japanese ⇒ I tried to make an English translation tool
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a strange quote for Jojo with LSTM
I tried to make a mechanism of exclusive control with Go
I tried to create a linebot (preparation)
I tried playing a ○ ✕ game using TensorFlow
I tried drawing a line using turtle
I tried using pipenv, so a memo
I tried to predict Covid-19 using Darts
Python: I tried to make a flat / flat_map just right with a generator
I tried to make a face diagnosis AI for a female professional golfer ①
I tried to make a face diagnosis AI for a female professional golfer ②
I learned scraping using selenium to make a horse racing prediction model.
I tried to make a calculator with Tkinter so I will write it
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to perform a cluster analysis of customers using purchasing data
I tried to create a sample to access Salesforce using Python and Bottle
I tried to make a skill that Alexa will return as cold
I tried to make a url shortening service serverless with AWS CDK
I tried to make PyTorch model API in Azure environment using TorchServe
I want to make a web application using React and Python flask
I want to make matplotlib a dark theme
I tried to build a super-resolution method / ESPCN
I tried to build a super-resolution method / SRCNN ①
I tried to synthesize WAV files using Pydub.
I want to make a game with Python
I tried to make AI for Smash Bros.
I tried using Pythonect, a dataflow programming language.
I tried reading a CSV file using Python
Sample to draw a simple clock using ebiten
I read "How to make a hacking lab"