pyqt 学习基础5 - 笔记软件的编辑器

笔记软件的编辑器

几个疑问

  1. 今天在试着为笔记软件写个编辑器,然后参考qt自带的textedit的示例。下面是一个撤销操作的一段代码,我就疑惑了,这跟用QPushButton应该差不多吧。

    self.actionUndo = QtGui.QAction(

    QtGui.QIcon.fromTheme(‘edit-undo‘,
                    QtGui.QIcon(rsrcPath + ‘/editundo.png‘)),
            "&Undo", self, shortcut=QtGui.QKeySequence.Undo)
    tb.addAction(self.actionUndo)
    menu.addAction(self.actionUndo)

代码比较没有注释

# -*- coding:utf8 -*-
import sip
sip.setapi(‘QString‘, 2)

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import mainQss
# NoDragCombo这个类是为了防止拖动Combobox所带来的bug
class NoDragCombo(QComboBox):
    def __init__(self, parent=None):
        QComboBox.__init__(self, parent)
    def mouseMoveEvent(self, QMouseEvent):
        pass
    def mouseReleaseEvent(self, QMouseEvent):
        pass
class NoDragFontCombo(QFontComboBox):
    def __init__(self, parent=None):
        QFontComboBox.__init__(self, parent)
    def mouseMoveEvent(self, QMouseEvent):
        pass
    def mouseReleaseEvent(self, QMouseEvent):
        pass

class CenterWidget(QWidget):
    def __init__(self, fileName=None, parent=None):
        QWidget.__init__(self, parent)
        self.initAllObjects()
        self.setupFileActions()
        self.setupEditActions()
        self.setupTextActions()
        self.setupTextEdit()
        self.setupStyleSheet()
        self.setupMainUi()
        self.fontChanged(self.textEdit.font())
        self.colorChanged(self.textEdit.textColor())
        self.alignmentChanged(self.textEdit.alignment())
        self.textEdit.document().modificationChanged.connect(
                self.actionSave.setEnabled)
        self.textEdit.document().modificationChanged.connect(
                self.setWindowModified)
        self.textEdit.document().undoAvailable.connect(
                self.actionUndo.setEnabled)
        self.textEdit.document().redoAvailable.connect(
                self.actionRedo.setEnabled)
        self.actionSave.setEnabled(self.textEdit.document().isModified())
        self.actionUndo.setEnabled(self.textEdit.document().isUndoAvailable())
        self.actionRedo.setEnabled(self.textEdit.document().isRedoAvailable())
        self.actionUndo.triggered.connect(self.textEdit.undo)
        self.actionRedo.triggered.connect(self.textEdit.redo)
        self.actionCut.setEnabled(False)
        self.actionCopy.setEnabled(False)
        self.actionCut.triggered.connect(self.textEdit.cut)
        self.actionCopy.triggered.connect(self.textEdit.copy)
        self.actionPaste.triggered.connect(self.textEdit.paste)
        self.textEdit.copyAvailable.connect(self.actionCut.setEnabled)
        self.textEdit.copyAvailable.connect(self.actionCopy.setEnabled)
        QtGui.QApplication.clipboard().dataChanged.connect(
                self.clipboardDataChanged)

    def initAllObjects(self):
        self.oneStyle = QStyleFactory.create("plastique")
        self.textEdit = QTextEdit(self)
        self.layout = QVBoxLayout(self)
        self.topLayout = QHBoxLayout()
        self.topWidget = QWidget(self)
        self.topWidgetLayout = QHBoxLayout(self.topWidget)
        self.fileBtn = QPushButton("File",self.topWidget)
        self.editBtn = QPushButton("Edit",self.topWidget)
        self.textBtn = QPushButton("Text",self.topWidget)
        self.comboFont = NoDragFontCombo(self.topWidget)
        self.comboSize = NoDragCombo(self.topWidget)
        self.comboStyle = NoDragCombo(self.topWidget)

    def setupStyleSheet(self):
        # self.fileBtn.setStyleSheet(mainQss.writeButton)
        # self.fileBtn.setGeometry(2, 1, 24, 24)
        # self.editBtn.setStyleSheet(mainQss.writeButton)
        # self.editBtn.setGeometry(28, 1, 24, 24)
        # self.textBtn.setStyleSheet(mainQss.writeButton)
        # self.textBtn.setGeometry(54, 1, 24, 24)
        # self.comboFont.setGeometry(80, 1, 100, 24)
        # self.comboSize.setGeometry(182, 1, 100, 24)
        # self.comboStyle.setGeometry(284, 1, 100, 24)
        self.fileBtn.setStyle(self.oneStyle)
        self.editBtn.setStyle(self.oneStyle)
        self.textBtn.setStyle(self.oneStyle)
        self.comboStyle.setStyle(self.oneStyle)
        self.comboSize.setStyle(self.oneStyle)
        self.comboFont.setStyle(self.oneStyle)
        self.topWidget.setMinimumHeight(26)
        # self.topWidget.setMaximumHeight(26)
        self.topWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
        self.topLayout.setContentsMargins(0, 0, 0, 0)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

    def setupTextEdit(self):
        self.textEdit.setFocus()
        oneFont = QFont("Times New Romane", 13, QFont.Normal, False)
        self.textEdit.setFont(oneFont)
        self.textEdit.currentCharFormatChanged.connect(
                self.currentCharFormatChanged)
        self.textEdit.cursorPositionChanged.connect(self.cursorPositionChanged)
        self.setCurrentFileName()

    def setupMainUi(self):
        self.topLayout.addWidget(self.topWidget)
        self.layout.addLayout(self.topLayout)
        self.layout.addWidget(self.textEdit)
        self.setLayout(self.layout)
        self.topWidgetLayout.addWidget(self.fileBtn)
        self.topWidgetLayout.addWidget(self.editBtn)
        self.topWidgetLayout.addWidget(self.textBtn)
        self.topWidgetLayout.addWidget(self.comboFont)
        self.topWidgetLayout.addWidget(self.comboSize)
        self.topWidgetLayout.addWidget(self.comboStyle)

    def setupFileActions(self):
        menu = QMenu("&File", self)
        self.fileBtn.setMenu(menu)
        self.actionNew = QAction("&New", self,
                priority=QAction.LowPriority,
                shortcut=QKeySequence.New,
                triggered=self.fileNew)
        menu.addAction(self.actionNew)

        self.actionNew = QtGui.QAction(
                "&New", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtGui.QKeySequence.New, triggered=self.fileNew)
        menu.addAction(self.actionNew)

        self.actionOpen = QtGui.QAction(
                "&Open...", self, shortcut=QtGui.QKeySequence.Open,
                triggered=self.fileOpen)
        menu.addAction(self.actionOpen)
        menu.addSeparator()

        self.actionSave = QtGui.QAction(
                "&Save", self, shortcut=QtGui.QKeySequence.Save,
                triggered=self.fileSave, enabled=False)
        menu.addAction(self.actionSave)

        self.actionSaveAs = QtGui.QAction("Save &As...", self,
                priority=QtGui.QAction.LowPriority,
                shortcut=QtCore.Qt.CTRL + QtCore.Qt.SHIFT + QtCore.Qt.Key_S,
                triggered=self.fileSaveAs)
        menu.addAction(self.actionSaveAs)
        menu.addSeparator()

        self.actionPrint = QtGui.QAction(
                "&Print...", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtGui.QKeySequence.Print, triggered=self.filePrint)
        menu.addAction(self.actionPrint)

        self.actionPrintPreview = QtGui.QAction(
                "Print Preview...", self,
                shortcut=QtCore.Qt.CTRL + QtCore.Qt.SHIFT + QtCore.Qt.Key_P,
                triggered=self.filePrintPreview)
        menu.addAction(self.actionPrintPreview)

        self.actionPrintPdf = QtGui.QAction(
                "&Export PDF...", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_D,
                triggered=self.filePrintPdf)
        menu.addAction(self.actionPrintPdf)
        menu.addSeparator()

        self.actionQuit = QtGui.QAction("&Quit", self,
                shortcut=QtGui.QKeySequence.Quit, triggered=self.close)
        menu.addAction(self.actionQuit)

    def setupEditActions(self):
        menu = QMenu("&Edit", self)
        self.editBtn.setMenu(menu)

        self.actionUndo = QtGui.QAction(
                "&Undo", self, shortcut=QtGui.QKeySequence.Undo)
        menu.addAction(self.actionUndo)

        self.actionRedo = QtGui.QAction(
                "&Redo", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtGui.QKeySequence.Redo)
        menu.addAction(self.actionRedo)
        menu.addSeparator()

        self.actionCut = QtGui.QAction(
                "Cu&t", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtGui.QKeySequence.Cut)
        menu.addAction(self.actionCut)

        self.actionCopy = QtGui.QAction(
                "&Copy", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtGui.QKeySequence.Copy)
        menu.addAction(self.actionCopy)

        self.actionPaste = QtGui.QAction(
                "&Paste", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtGui.QKeySequence.Paste,
                enabled=(len(QtGui.QApplication.clipboard().text()) != 0))
        menu.addAction(self.actionPaste)

    def fileNew(self):
        print "create new file"
        if self.maybeSave():
            self.textEdit.clear()
            self.setCurrentFileName()

    def fileOpen(self):
        print "open file"
        fn = QFileDialog.getOpenFileName(self, "Open File...", None,
                "HTML-Files (*.htm *html);;ALL Files (*)")
        if fn:
            self.load(fn)

    def filePrint(self):
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
        dlg = QtGui.QPrintDialog(printer, self)

        if self.textEdit.textCursor().hasSelection():
            dlg.addEnabledOption(QtGui.QAbstractPrintDialog.PrintSelection)

        dlg.setWindowTitle("Print Document")

        if dlg.exec_() == QtGui.QDialog.Accepted:
            self.textEdit.print_(printer)

        del dlg

    def filePrintPdf(self):
        print "print pdf"
        fn = QtGui.QFileDialog.getSaveFileName(self, "Export PDF", None,
                "PDF files (*.pdf);;All Files (*)")

        if fn:
            if QtCore.QFileInfo(fn).suffix().isEmpty():
                fn += ‘.pdf‘

            printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
            printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
            printer.setOutputFileName(fileName)
            self.textEdit.document().print_(printer)

    def printPreview(self, printer):
        self.textEdit.print_(printer)

    def filePrintPreview(self):
        print "print Preview"
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
        preview = QtGui.QPrintPreviewDialog(printer, self)
        preview.paintRequested.connect(self.printPreview)
        preview.exec_()

    def fileSave(self):
        print "save file"
        if not self.fileName:
            return self.fileSaveAs()
        writer = QTextDocumentWriter(self.fileName)
        success = writer.write(self.textEdit.document())
        if success:
            self.textEdit.document().setModified(False)
        return success

    def fileSaveAs(self):
        print "file save as"
        fn = QtGui.QFileDialog.getSaveFileName(self, "Save as...", "C:/",
                "ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)")
        if not fn:
            return False

        lfn = fn.lower()
        if not lfn.endswith((‘.odt‘, ‘.htm‘, ‘.html‘)):
            # The default.
            fn += ‘.odt‘

        self.setCurrentFileName(fn)
        return self.fileSave()

    def load(self, f):
        if not QtCore.QFile.exists(f):
            return False

        fh = QtCore.QFile(f)
        if not fh.open(QtCore.QFile.ReadOnly):
            return False

        data = fh.readAll()
        codec = QtCore.QTextCodec.codecForHtml(data)
        unistr = codec.toUnicode(data)

        if QtCore.Qt.mightBeRichText(unistr):
            self.textEdit.setHtml(unistr)
        else:
            self.textEdit.setPlainText(unistr)

        self.setCurrentFileName(f)
        return True

    def maybeSave(self):
        if not self.textEdit.document().isModified():
            return True

        if self.fileName.startswith(‘:/‘):
            return True

        ret = QtGui.QMessageBox.warning(self, "Application",
                "The document has been modified.\n"
                "Do you want to save your changes?",
                QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
                        QtGui.QMessageBox.Cancel)

        if ret == QtGui.QMessageBox.Save:
            return self.fileSave()

        if ret == QtGui.QMessageBox.Cancel:
            return False

        return True

    def setupTextActions(self):
        menu = QtGui.QMenu("F&ormat", self)
        self.textBtn.setMenu(menu)

        self.actionTextBold = QtGui.QAction(
                "&Bold", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_B,
                triggered=self.textBold, checkable=True)
        bold = QtGui.QFont()
        bold.setBold(True)
        self.actionTextBold.setFont(bold)
        menu.addAction(self.actionTextBold)

        self.actionTextItalic = QtGui.QAction(
                "&Italic", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_I,
                triggered=self.textItalic, checkable=True)
        italic = QtGui.QFont()
        italic.setItalic(True)
        self.actionTextItalic.setFont(italic)
        menu.addAction(self.actionTextItalic)

        self.actionTextUnderline = QtGui.QAction(
                "&Underline", self, priority=QtGui.QAction.LowPriority,
                shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_U,
                triggered=self.textUnderline, checkable=True)
        underline = QtGui.QFont()
        underline.setUnderline(True)
        self.actionTextUnderline.setFont(underline)
        menu.addAction(self.actionTextUnderline)

        menu.addSeparator()

        grp = QtGui.QActionGroup(self, triggered=self.textAlign)

        # Make sure the alignLeft is always left of the alignRight.
        if QtGui.QApplication.isLeftToRight():
            self.actionAlignLeft = QtGui.QAction(
                    "&Left", grp)
            self.actionAlignCenter = QtGui.QAction(
                    "C&enter", grp)
            self.actionAlignRight = QtGui.QAction(
                    "&Right", grp)
        else:
            self.actionAlignRight = QtGui.QAction(
                    "&Right", grp)
            self.actionAlignCenter = QtGui.QAction(
                    "C&enter", grp)
            self.actionAlignLeft = QtGui.QAction(
                    "&Left", grp)

        self.actionAlignJustify = QtGui.QAction(
                "&Justify", grp)

        self.actionAlignLeft.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_L)
        self.actionAlignLeft.setCheckable(True)
        self.actionAlignLeft.setPriority(QtGui.QAction.LowPriority)

        self.actionAlignCenter.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_E)
        self.actionAlignCenter.setCheckable(True)
        self.actionAlignCenter.setPriority(QtGui.QAction.LowPriority)

        self.actionAlignRight.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_R)
        self.actionAlignRight.setCheckable(True)
        self.actionAlignRight.setPriority(QtGui.QAction.LowPriority)

        self.actionAlignJustify.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_J)
        self.actionAlignJustify.setCheckable(True)
        self.actionAlignJustify.setPriority(QtGui.QAction.LowPriority)

        menu.addSeparator()

        pix = QtGui.QPixmap(16, 16)
        pix.fill(QtCore.Qt.black)
        self.actionTextColor = QtGui.QAction(QtGui.QIcon(pix), "&Color...",
                self, triggered=self.textColor)
        menu.addAction(self.actionTextColor)

        self.comboStyle.addItem("Standard")
        self.comboStyle.addItem("Bullet List (Disc)")
        self.comboStyle.addItem("Bullet List (Circle)")
        self.comboStyle.addItem("Bullet List (Square)")
        self.comboStyle.addItem("Ordered List (Decimal)")
        self.comboStyle.addItem("Ordered List (Alpha lower)")
        self.comboStyle.addItem("Ordered List (Alpha upper)")
        self.comboStyle.addItem("Ordered List (Roman lower)")
        self.comboStyle.addItem("Ordered List (Roman upper)")
        self.comboStyle.activated.connect(self.textStyle)
        self.comboFont.activated[str].connect(self.textFamily)
        self.comboSize.setObjectName("comboSize")
        self.comboSize.setEditable(True)
        db = QtGui.QFontDatabase()
        for size in db.standardSizes():
            self.comboSize.addItem("%s" % (size))
        self.comboSize.activated[str].connect(self.textSize)
        self.comboSize.setCurrentIndex(
                self.comboSize.findText(
                        "%s" % (QtGui.QApplication.font().pointSize())))

    def textAlign(self):
        print "text align"
    def textBold(self):
        print "text bold"
        fmt = QTextCharFormat()
        fmt.setFontWeight(self.actionTextBold.isChecked() and
                QFont.Bold or QFont.Normal)
        self.mergeFormatOnWordOrSelection(fmt)

    def textUnderline(self):
        fmt = QtGui.QTextCharFormat()
        fmt.setFontUnderline(self.actionTextUnderline.isChecked())
        self.mergeFormatOnWordOrSelection(fmt)

    def textItalic(self):
        fmt = QtGui.QTextCharFormat()
        fmt.setFontItalic(self.actionTextItalic.isChecked())
        self.mergeFormatOnWordOrSelection(fmt)

    def textFamily(self, family):
        fmt = QtGui.QTextCharFormat()
        fmt.setFontFamily(family)
        self.mergeFormatOnWordOrSelection(fmt)

    def textSize(self, pointSize):
        pointSize = float(pointSize)
        if pointSize > 0:
            fmt = QtGui.QTextCharFormat()
            fmt.setFontPointSize(pointSize)
            self.mergeFormatOnWordOrSelection(fmt)

    def textStyle(self, styleIndex):
        cursor = self.textEdit.textCursor()
        if styleIndex:
            styleDict = {
                1: QtGui.QTextListFormat.ListDisc,
                2: QtGui.QTextListFormat.ListCircle,
                3: QtGui.QTextListFormat.ListSquare,
                4: QtGui.QTextListFormat.ListDecimal,
                5: QtGui.QTextListFormat.ListLowerAlpha,
                6: QtGui.QTextListFormat.ListUpperAlpha,
                7: QtGui.QTextListFormat.ListLowerRoman,
                8: QtGui.QTextListFormat.ListUpperRoman,
            }

            style = styleDict.get(styleIndex, QtGui.QTextListFormat.ListDisc)
            cursor.beginEditBlock()
            blockFmt = cursor.blockFormat()
            listFmt = QtGui.QTextListFormat()

            if cursor.currentList():
                listFmt = cursor.currentList().format()
            else:
                listFmt.setIndent(blockFmt.indent() + 1)
                blockFmt.setIndent(0)
                cursor.setBlockFormat(blockFmt)

            listFmt.setStyle(style)
            cursor.createList(listFmt)
            cursor.endEditBlock()
        else:
            bfmt = QtGui.QTextBlockFormat()
            bfmt.setObjectIndex(-1)
            cursor.mergeBlockFormat(bfmt)

    def textColor(self):
        col = QtGui.QColorDialog.getColor(self.textEdit.textColor(), self)
        if not col.isValid():
            return

        fmt = QtGui.QTextCharFormat()
        fmt.setForeground(col)
        self.mergeFormatOnWordOrSelection(fmt)
        self.colorChanged(col)

    def textAlign(self, action):
        if action == self.actionAlignLeft:
            self.textEdit.setAlignment(
                    QtCore.Qt.AlignLeft | QtCore.Qt.AlignAbsolute)
        elif action == self.actionAlignCenter:
            self.textEdit.setAlignment(QtCore.Qt.AlignHCenter)
        elif action == self.actionAlignRight:
            self.textEdit.setAlignment(
                    QtCore.Qt.AlignRight | QtCore.Qt.AlignAbsolute)
        elif action == self.actionAlignJustify:
            self.textEdit.setAlignment(QtCore.Qt.AlignJustify)
    def mergeFormatOnWordOrSelection(self, format):
        cursor = self.textEdit.textCursor()
        if not cursor.hasSelection():
            cursor.select(QtGui.QTextCursor.WordUnderCursor)

        cursor.mergeCharFormat(format)
        self.textEdit.mergeCurrentCharFormat(format)

    def currentCharFormatChanged(self, format):
        self.fontChanged(format.font())
        self.colorChanged(format.foreground().color())
    def cursorPositionChanged(self):
        self.alignmentChanged(self.textEdit.alignment())
    def clipboardDataChanged(self):
        self.actionPaste.setEnabled(
                len(QtGui.QApplication.clipboard().text()) != 0)
    def setCurrentFileName(self, fileName=‘‘):
        self.fileName = fileName
        self.textEdit.document().setModified(False)

        if not fileName:
            shownName = ‘untitled.txt‘
        else:
            shownName = QtCore.QFileInfo(fileName).fileName()

        self.setWindowTitle(self.tr("%s[*] - %s" % (shownName, "Rich Text")))
        self.setWindowModified(False)
    def colorChanged(self, color):
        pix = QtGui.QPixmap(16, 16)
        pix.fill(color)
        self.actionTextColor.setIcon(QtGui.QIcon(pix))
    def alignmentChanged(self, alignment):
        if alignment & QtCore.Qt.AlignLeft:
            self.actionAlignLeft.setChecked(True)
        elif alignment & QtCore.Qt.AlignHCenter:
            self.actionAlignCenter.setChecked(True)
        elif alignment & QtCore.Qt.AlignRight:
            self.actionAlignRight.setChecked(True)
        elif alignment & QtCore.Qt.AlignJustify:
            self.actionAlignJustify.setChecked(True)
    def fontChanged(self, font):
        self.comboFont.setCurrentIndex(
                self.comboFont.findText(QtGui.QFontInfo(font).family()))
        self.comboSize.setCurrentIndex(
                self.comboSize.findText("%s" % font.pointSize()))
        self.actionTextBold.setChecked(font.bold())
        self.actionTextItalic.setChecked(font.italic())
        self.actionTextUnderline.setChecked(font.underline())

class mainUi(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setupSomeVariable()
        self.setupMainUi() # create all button,widget and so on

        self.connect(self.btnClose, SIGNAL("clicked()"), QtGui.qApp,                 SLOT("quit()"))
        self.connect(self.btnMini, SIGNAL("clicked()"),self.showMinimized)
        self.connect(self.btnMax, SIGNAL("clicked()"),self.showMaxNor)

    def setupSomeVariable(self):
        pass

    def setupMainUi(self):
        self.layout = QHBoxLayout(self) # main layout

        # three widget, left-center-right
        self.leftwidget = QWidget()
        self.centerwidget = CenterWidget()
        self.rightwidget = QWidget()
        self.leftwidget.setMaximumWidth(300)
        self.leftwidget.setMinimumWidth(200)
        self.leftwidget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) # growflag
        self.centerwidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # growflag
        self.rightwidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) # growflag
        self.centerwidget.setMinimumWidth(550)
        self.rightwidget.setMinimumWidth(250)
        self.rightwidget.setMaximumWidth(300)

        self.centerwidget.setObjectName(‘name‘)
        # customize the three widget
        self.leftwidget.setStyleSheet(mainQss.threeWidget)
        #self.centerwidget.setStyleSheet(mainQss.threeWidget)
        self.rightwidget.setStyleSheet(mainQss.threeWidget)

        # to show user headportrait
        headLabel = QLabel(self.rightwidget)
        headLabel.setStyleSheet(mainQss.headLabel)
        headLabel.setGeometry(25, 50, 80, 80)

        # set several button
        self.blogButton = QPushButton(u‘我的博客‘,self.rightwidget)
        self.blogButton.setStyleSheet(mainQss.textButton)
        self.blogButton.setGeometry(25, 180, 150, 30)
        self.blogWriteButton = QPushButton(self.rightwidget)
        self.blogWriteButton.setStyleSheet(mainQss.writeButton)
        self.blogWriteButton.setGeometry(180, 182, 24, 24)

        self.noteButton = QPushButton(u‘日常笔记‘,self.rightwidget)
        self.noteButton.setStyleSheet(mainQss.textButton)
        self.noteButton.setGeometry(25, 220, 150, 30)
        self.noteWriteButton = QPushButton(self.rightwidget)
        self.noteWriteButton.setStyleSheet(mainQss.writeButton)
        self.noteWriteButton.setGeometry(180, 222, 24, 24)

        self.taskButton = QPushButton(u‘今日任务‘,self.rightwidget)
        self.taskButton.setStyleSheet(mainQss.textButton)
        self.taskButton.setGeometry(25, 260, 150, 30)
        self.taskWriteButton = QPushButton(self.rightwidget)
        self.taskWriteButton.setStyleSheet(mainQss.writeButton)
        self.taskWriteButton.setGeometry(180, 262, 24, 24) 

        self.btnClose = QPushButton(self.leftwidget)
        self.btnMini = QPushButton(self.leftwidget)
        self.btnMax = QPushButton(self.leftwidget)
        self.btnClose.setGeometry(5, 5, 24, 24)
        self.btnMini.setGeometry(64, 5, 24, 24)
        self.btnMax.setGeometry(35, 5, 24, 24)
        self.btnClose.setStyleSheet(mainQss.btn_close)
        self.btnMini.setStyleSheet(mainQss.btn_mini)
        self.btnMax.setStyleSheet(mainQss.btn_max)

        # create three sub layout
        self.leftLayout = QVBoxLayout()
        self.centerLayout = QVBoxLayout()
        self.rightLayout = QVBoxLayout()
        self.leftLayout.addWidget(self.leftwidget)
        self.centerLayout.addWidget(self.centerwidget)
        self.rightLayout.addWidget(self.rightwidget)
        self.layout.addLayout(self.leftLayout)
        self.layout.addLayout(self.centerLayout)
        self.layout.addLayout(self.rightLayout)

        # customize main layout
        self.layout.setContentsMargins(0,0,0,0)
        self.layout.setSpacing(0)
        self.setLayout(self.layout)
        self.setWindowOpacity(0.9)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Ignored)
        self.resize(1000, 600)

    def showMaxNor(self):
        if self.isMaximized():
            self.showNormal()
            self.maxToNor = False
        else:
            self.showMaximized()
            self.maxToNor = True

    def mousePressEvent(self, event):
        if self.isMaximized():
            return
        if event.button() == Qt.LeftButton:
            self.dragPos = event.globalPos() - self.pos()
            event.accept()

    def mouseMoveEvent(self, QMouseEvent):
        if self.isMaximized():
            return
        if QMouseEvent.buttons() and Qt.LeftButton:
            self.move(QMouseEvent.globalPos() - self.dragPos)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        pass

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    mu = mainUi()
    mu.show()
    sys.exit(app.exec_())

上图

时间: 08-29

pyqt 学习基础5 - 笔记软件的编辑器的相关文章

pyqt 学习基础 实践2 基于oschina笔记软件的初步界面

笔记软件主界面 这东西大概介绍 我想做一个基于oschina的跨平台的笔记软件(做得好就分享给大家,做的不好就自己收藏-.,oschina openapi方面已经熟悉了一下,但是Qt还不是很熟悉,因为还是学习中-),下面讲我在用其他的笔记软件常常遇到以下几个问题: 不跨平台,因为很多像我这种伪程序猿都会在window和linux或者mac之间切换,像onenote就只能在windows上运行, 还有印象笔记的linux客户端也不甚理想.不过近期发现的为知笔记的确是个不错的选择 作为一个笔记软件,

pyqt学习基础 4 -插曲- python 正则表达式学习

python 正则表达式学习 资源来自 学习资源来自ubuntu wiki 正则表达式介绍 正则表达式,各种语言都有相关的库.就其本质而言,正则表达式(或 RE)是一种小型的.高度专业化的编程语言 简单模式 字符匹配 _大多数_字母和字符一般都会和自身匹配.例如,正则表达式 test 会和字符串"test"完全匹配. 正则表达式使用一些元字符来帮助字符匹配: . ^ $ * + ? { [ ] \ | ( ) "[" 和 "]" "[&

pyqt 学习基础 4 - creater的一点使用心得

qt creater 的使用 前言 个人认为 qt creater是个好东西,但是前提是要写过qt代码,不然拿着这个好东西也不知道干什么. 对了,qt creater.exe它的目录是在Python目录下-我的是这样,D:\Python27\Lib\site-packages\PyQt4 Qt creater 的作用 我现在在使用时,经常想要一些功能,但是不知道哪个组件实现更好,这时候,我就回去各种google,baidu ,qt实例(虽然大部分都是c++的),然后看到我想要的效果,我就用自己用

linux学习笔记--vim程序编辑器

1,在linux系统中使用文本编辑器来编辑自己的linux参数配置文件是一件很重要的事情,因此系统管理员至少应该要熟悉一种文本编辑器. 2,不同的linux distribution各有不同的附加软件,linux命令行界面下的文本编辑器有Emacs,pico,nano,joe与vim 3,学习vim的重要性 (1)所有的UNIX Like系统都内置vi文本编辑器,其他的文本编辑器不一定存在 (2)很多软件的编辑接口都会主动调用vi (3)vim具有程序编辑的能力,可以主动以字体颜色辨别语法的正确

Python学习的个人笔记(基础语法)

Python学习的个人笔记 题外话: 我是一个大二的计算机系的学生,这份python学习个人笔记是趁寒假这一周在慕课网,w3cschool,还有借鉴了一些博客,资料整理出来的,用于自己方便的时候查阅,一开始保存在word上,代码不是很好看,于是决定复制到博客里面,可能有复制过程中出错的,或者我本身在理解方面有出错的地方,希望能得到指正,谢谢  后续的内容我会继续学习…… python下载地址  www.python.org Python 分为2.7和3.3两个版本,3.3有些库不兼容,因此用2.

pyqt treeview基础学习

# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' from PyQt4.QtGui import  * from PyQt4.Qt import * from PyQt4.QtCore import * import sys class Tree(QTreeView): def __init__(self,parnet=None,*args): super(Tree,self).__init__(parnet,*a

《学习bash》笔记--基础shell编程

1.shell脚本和函数 脚本是包含shell命令的文件,它是一个shell程序,有三种方式运行它们: 一是键入source scriptname,使得脚本的命令被读取并运行,就好像键入它们一样. 二是运行bash scriptname,打开一个子shell来读取并执行脚本文件中命令.该脚本文件可以无"执行权限". 三是使用./scriptname,打开一个子shell读取并执行脚本文件中的命令,该脚本需要"执行权限". 1.1.函数 函数是一种脚本内脚本,你使用它

pyqt listview基础学习01

from decimal import * from PyQt4.QtGui import * from PyQt4.Qt import * from PyQt4.QtCore import * import sys class Example(QWidget): def __init__(self,args=None): super(Example, self).__init__(args) list_data=[1,2,3,4] lm=MyListMode(list_data,self) s

imooc’s html 基础教程笔记

imooc’s html 基础教程笔记 imooc’s html 基础教程 第一章 Html介绍 1.1 Html和CSS的关系 1.2认识html标签 1.3 标签的语法 1.4 认识html文件基本结构 1.5 认识head标签 1.6了解HTML的代码注释 2.1语义化,让你的网页更好的被搜索引擎理解 2.2 标签,网页上显示的内容放在这里 2.3 开始学习标签,添加段落 2.4 了解标签,为你的网页添加标题 2.5 加入强调语气,使用strong和em标签 2.6 使用span标签为文字