Pyqt practice: Production of simple notes

Source: Internet
Author: User
Tags emit
Why do notes software be written?
  • I have always had the idea of making a note software, and a special feature I designed for the note software is its note function. However, the note-taking software cannot be completed for various reasons, but his note function can also be separated from the notes. However, the function also changes accordingly.
  • We may need a schedule every day to help us work more efficiently. On Windows, we may use its own notes software and some other release versions, but I think they are unfriendly. So I am very much looking forward to a notes with outstanding functions. (This one I wrote is only a prototype and needs to be processed later)
What features does it have?
  • I have talked with several students. From the user's perspective, a note must be simple first, and the operations must be simple. The interface should not be fancy and practical.
Notes development functions
  1. Add, delete, modify, and edit events, Tray icons, and Windows global shortcuts (implemented)

  2. Alarm reminder function (not implemented)

  3. Save "events" (the previous "events" can still be displayed after Shutdown and restart) (not implemented)

  4. Desktop floating reminder, animation interaction on the interface... And so on (not implemented)

    These functions are not just to be implemented. We can use some means to make these common functions more popular with users, such as the alarm prompt: you can add a friendly little feature, such as, when the user has been using the computer for a long time, the notes are automatically issued with some personalized reminders. (This is just a direction of function divergence)

Notes page


Document Structure
  • widget.py: Program running portal, main interface implementation
  • 'Trayicon ': responsible for implementing the system tray Function
  • 'Mylabel, mybutton, mymeny': Reload some QT classes to implement custom components.
GitHub

https://github.com/zjuysw/memo.git

Explains how to use pyqt from a functional perspective

> If you have not used any software, you may not understand the following code annotations.

Main Interface Layout
  • The main interface uses hboxlayout, which contains two vboxlayout. (There is no difficulty in implementation)
Key front-end technologies
  • Set the background image on the main interface: qpalette. Note: Using stylesheet will inherit child widgets. (Widget. py)

    backImg = QPixmap(‘./img/1.png‘).scaled(self.size())palette = QPalette()palette.setBrush(self.backgroundRole(), QBrush(backImg))self.setPalette(palette)
  • Background Image and style of the icon: stylesheet

  • Special Effect (transparent): qgraphicsopacityeffect (mylable. py)

    self.opacity = QGraphicsOpacityEffect()self.opacity.setOpacity(0.7)self.setGraphicsEffect(self.opacity)
Notes dragging Technology
  • It is mainly used to override the mouse event of the widget (mylable. py)

    Def mousepressevent (self, event): If event. button () = QT. leftbutton: Self. dragpos = event. globalpos ()-self. POs () event. accept () def mousemoveevent (self, qmouseevent): pw = self. parentwidget () # obtain the parent widget, that is, the main widget widget1 = pw in this program. gettrashrect () # retrieve the bin widget of the main widget (function name is not changed) Flag = self. iscollide (widget1, self) # detects the collision between two widgets if flag: Self. emit (signal ('colexternetrash '), true) # The colexternetrash signal else: Self. emit (signal ('colexternal'), false) # use the following code to drag and drop a widget if qmouseevent. buttons () = QT. leftbutton: Self. move (qmouseevent. globalpos ()-self. dragpos) qmouseevent. accept () If qmouseevent. buttons () = QT. rightbutton: qmouseevent. ignore () def mousereleaseevent (self, qmouseevent): # After the drag and drop operation is complete, check whether the widget is collided to determine whether it is deleted PW = self. parentwidget () widget1 = pw. gettrashrect () Flag = self. iscollide (widget1, self) If flag: Print "yes" self. emit (signal ('colemediate'), false) self. hide () self. destroy () else: Self. emit (signal ('colemediate'), false) self. hide () self. show ()
    Custom signal sending and receiving technology
  • The following code roughly represents the core content of this technology (for actual use, please refer to the application in the complete project code)

    parentWidget = QWidget()subWidget = QWidget(parentWidget)subWidget.emit(SIGNAL("sub"))parentWidget.connect(subWidget, SIGNAL("sub"), parentWidget.doSomething)
Display and edit Replacement Technology
  • Idea: a layout contains two layout widgets, including content lable, time lable, edit box textedit, and OK button. When you want to display the content, we can hide the edit box and button. When editing, we can hide the content and time. (Mylable. py)

    def mouseDoubleClickEvent(self, event):    if event.button() == Qt.LeftButton:        self.label.hide()        self.timeLabel.hide()        self.textEdit.show()        self.textEdit.setFocus()        self.textEdit.setText(self.label.text())        self.okBtn.show()
Widget Collision Detection Technology
  • Idea: assume that the garbage bin is widget1 and lable is widget2. Since the bin is displayed in the lower left corner of the lable at the beginning, if they collide (overlap), there will inevitably be:The upper-right corner of widget2 is in the upper-right corner of the lower-left corner of widget1. The lower-left corner of widget2 must be in the lower-left corner of the upper-right corner of widget1.

    def isCollide(self, widget1, widget2):    dict1 = {}    dict1[‘size‘] = widget1.size()    dict1[‘pos‘] = widget1.pos()    dict2 = {}    dict2[‘size‘] = widget2.size()    dict2[‘pos‘] = widget2.pos()    r1TopRightX = dict1[‘pos‘].x() + dict1[‘size‘].width()    r1TopRightY = dict1[‘pos‘].y()    r1BottomLeftX = dict1[‘pos‘].x()    r1BottomLeftY = dict1[‘pos‘].y() + dict1[‘size‘].height()    r2TopRightX = dict2[‘pos‘].x() + dict2[‘size‘].width()    r2TopRightY = dict2[‘pos‘].y()    r2BottomLeftX = dict2[‘pos‘].x()    r2BottomLeftY = dict2[‘pos‘].y() + dict2[‘size‘].height()    if r1TopRightX > r2BottomLeftX and r1TopRightY < r2BottomLeftY             and r2TopRightX > r1BottomLeftX and r2TopRightY < r1BottomLeftY:                return True    else:        return False
Edit focus Detection
  • Use qfocusevent (mylable. py) of qtextedit directly)

    def focusInEvent(self, event):    print "edit"    self.emit(SIGNAL("Editing"))def focusOutEvent(self, event):    if event.reason() == 4: # popup focus        event.ignore()    else:        self.emit(SIGNAL("EditFinish"))
Global Shortcut Key Technology for Windows
  • Use the python ctypes module (QT itself does not have a corresponding global shortcut key processing class) (hotkey. py)

    #!/usr/bin/env python# -*- coding: utf8-*-import sysimport timefrom ctypes import *from ctypes.wintypes import *from PyQt4.QtGui import QApplicationimport widgetdelta = 0.3lastTime = 0WM_HOTKEY   = 0x0312MOD_ALT     = 0x0001MOD_CONTROL = 0x0002MOD_SHIFT   = 0x0004WM_KEYUP    = 0x0101class MSG(Structure):    _fields_ = [(‘hwnd‘, c_int),                (‘message‘, c_uint),                (‘wParam‘, c_int),                (‘lParam‘, c_int),                (‘time‘, c_int),                (‘pt‘, POINT)]key = 192 # ~ keyhotkeyId = 1if not windll.user32.RegisterHotKey(None, hotkeyId, None, key):    sys.exit("Cant Register Hotkey")msg = MSG()app = QApplication(sys.argv)w = widget.mainUi()while True:    if (windll.user32.GetMessageA(byref(msg), None, 0, 0) != 0):        if msg.message == WM_HOTKEY and msg.wParam == hotkeyId:            if (time.time() - lastTime) < delta:                w.show()            else:                pass            lastTime = time.time()        if msg.message == WM_KEYUP:            print "up"            w.myHide()        windll.user32.TranslateMessage(byref(msg))        windll.user32.DispatchMessageA(byref(msg))
System Tray Technology
  • Basically, let's look at the pyqt documentation (trayicon. py)

    #-*-Coding: utf8-*-import sysfrom pyqt4 import qtcore, qtguifrom pyqt4.qtcore import * From pyqt4.qtgui import * class trayicon (qsystemtrayicon): def _ init _ (self, parent = none): Super (trayicon, self ). _ init _ (parent) self. initobjects () self. setobjects () self. activated. connect (self. iconclicked) def initobjects (Self): Self. menu = qmenu () self. quitaction = qaction (U "quit", self, triggered = self. exitapp) self. icon = qicon ('. /img/icon.png ') def setobjects (Self): Self. menu. addaction (self. quitaction) self. seticon (self. icon) self. setcontextmenu (self. menu) def iconclicked (self, reason): Print reason if reason = 2 or reason = 3: pw = self. parent () if PW. isvisible (): pw. hide () else: pw. show () def exitapp (Self): Self. setvisible (false) qapp. quit () sys. exit () If _ name _ = "_ main _": Import sys APP = qapplication (sys. argv) Ti = trayicon () Ti. show () sys.exit(app.exe C _())
Summary

It seems that you have encountered some difficult technical problems in the process of writing, but the key is to learn some basic knowledge of pyqt, and think clearly about the requirements when organizing the software, clarify the software structure. Welcome _ discussion _ and _ correction _ or _ to propose better methods and suggestions _. There will always be unexpected surprises in the collision of ideas

Pyqt practice: Production of simple notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.