4

I need to update the existing menu items for a system tray application. At first when the app loads, there will be two menu items. Later when I click a button these menu items need to be replaced with new menu items. How can I achieve that ? Here is my code.

from PySide.QtGui import *
import sys

class MainWindow(QMainWindow):
  def __init__(self):
    super(MainWindow, self).__init__()

    self.tray = QSystemTrayIcon(QApplication.style().standardIcon(QStyle.SP_DriveDVDIcon), self)
    self.m = QMenu()
    self.m.addAction('First')
    self.m.addAction('Second')
    self.tray.setContextMenu(self.m)
    self.tray.show()

    p = QPushButton("Click Me", self)
    self.setCentralWidget(p)
    p.clicked.connect(self.onClick)

  def onClick(self):
    self.m.clear()
    self.m.addAction('First')
    self.m.addAction('Third')
    self.tray.setContextMenu(self.m)

app = QApplication(sys.argv)
w = MainWindow()
w.show();
sys.exit(app.exec_())

However this is not working. If I try removing self.m.clear()the new menu items will append to the existing (Which is the normal behaviour in this case). Isn't menu.clear() clears the current menu & the new menu should be populated here ?

I have seen this similar question Qt QSystemTrayIcon change menu items and the solution doesn't work for me. I am running Ubuntu 14.04.

Community
  • 1
  • 1
Jakes
  • 105
  • 1
  • 7
  • 1
    Your code works for me with PySide 1.2.2 on Windows 8.0 (Python 2.7.3-32bit). Initially the menu has "first" and "Second" entries. When I click the button the menu has "first" and "third" entries. It seems like a platform specific issue (maybe even with Qt itself). – three_pineapples Jul 20 '14 at 07:23
  • 2
    In KDE (Kubuntu) your code works as it should. Probably is a bug in Ubuntu Unity UI. – doru Jul 20 '14 at 08:07
  • As with Ubuntu,it also doesn't work with Elementary OS. EOS doesn't use Unity (Correct me if I am wrong). As @doru pointed out, it works in Kubuntu (Checked in 13.04) – nbk Jul 20 '14 at 10:06

1 Answers1

2

I figured it out, the problem is due to the self.tray.setContextMenu(self.m). Remove this line from onClick method. This should work fine on Ubuntu.

qurban
  • 3,885
  • 24
  • 36
  • 2
    Yes, that was it. Now its working on both Windows & Ubuntu. Still don't know why it earlier worked in all other platforms except Ubuntu :-/ – Jakes Jul 21 '14 at 10:57