我编写了一个程序,在系统托盘中创建一个图标,然后单击鼠标右键显示3点注释,创建新笔记和退出的上下文菜单,按下菜单应该出现创建新笔记表单,但它没有出现。为什么呢?
from PyQt4 import QtCore, QtGui, uic
import sys
class NoteForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
uic.loadUi("note.ui", self)
def main():
app = QtGui.QApplication(sys.argv)
tray = QtGui.QSystemTrayIcon()
icon = app.style().standardIcon(QtGui.QStyle.SP_DesktopIcon)
tray.setIcon(icon)
tray.show()
CreateMenu(tray, app)
sys.exit(app.exec_())
def CreateMenu(tray, app):
m1 = QtGui.QMenu("Menu 1")
m2 = QtGui.QMenu("Notes", m1)
actNewNote=QtGui.QAction("Create new note", m1)
actNewNote.triggered.connect(viewNote)
#m1.addAction("Create new note", viewNote)
m1.addMenu(m2)
m1.addSeparator()
m1.addAction("Quit", app.quit)
tray.setContextMenu(m1)
def viewNote():
note=NoteForm()
note.show()
if __name__ == '__main__':
main()
note.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>WindowNote</class>
<widget class="QDialog" name="WindowNote">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>707</width>
<height>356</height>
</rect>
</property>
<property name="windowTitle">
<string>Заметка</string>
</property>
<widget class="QWidget" name="">
<property name="geometry">
<rect>
<x>20</x>
<y>10</y>
<width>671</width>
<height>331</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="3">
<widget class="QLineEdit" name="TitleNote"/>
</item>
<item row="1" column="0" colspan="3">
<widget class="QTextEdit" name="textNote"/>
</item>
<item row="2" column="0">
<widget class="QPushButton" name="buttonOK">
<property name="text">
<string>OK</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="buttonCancel">
<property name="text">
<string>Отмена</string>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QPushButton" name="buttonDeleteNote">
<property name="text">
<string>Удалить заметку</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
答案 0 :(得分:1)
viewNote
函数不会保存对其创建的NoteForm
实例的引用。 show()
函数会立即返回而不会阻塞,因此对话框在显示后会直接进行垃圾回收。
要解决此问题,请使用exec_运行对话框,或保留全局引用:
def viewNote():
note = NoteForm()
note.exec_()
或:
def viewNote():
global note
note = NoteForm()
note.show()
答案 1 :(得分:0)
您必须在QDialog.exec_()
中添加viewNote()
。并启用Create new Note
操作。像这样:
def CreateMenu(tray, app):
m1 = QtGui.QMenu("Menu 1")
m2 = QtGui.QMenu("Notes", m1)
actNewNote=QtGui.QAction("Create new note", m1)
actNewNote.triggered.connect(viewNote)
m1.addAction("Create new note", viewNote)
m1.addMenu(m2)
m1.addSeparator()
m1.addAction("Quit", app.quit)
tray.setContextMenu(m1)
def viewNote():
note=NoteForm()
note.show()
note.exec_()
或者您可以将note
作为全局传递,如下所示:
def viewNote():
global note
note = NoteForm()
note.show()