How can i use QGroupBox with two views? - python-3.x

i have two views (first and second) vertical aligment
import sys
from PyQt5.QtWidgets import QMainWindow,QSplitter,QGroupBox, QApplication, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout
from PyQt5.QtGui import QPainter, QColor, QFont
from PyQt5.QtCore import Qt
from .First import First
from .Second import Second
class LateralMenu(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.plotview = QGroupBox("Group of views")
self.text = "Menu Lateral"
self.layout = QSplitter(Qt.Vertical)
self.layout_plotview = QVBoxLayout()
self.First = First()
self.Second = Second()
self.layout.addWidget(self.First)
self.layout.addWidget(self.Second)
self.layout_plotview.addWidget(self.layout)
self.plotview.setLayout(self.layout_plotview)
self.setLayout(self.plotview)
i want to put those views in a QGroupBox, but i am getting this error: self.setLayout(self.plotview)
TypeError: setLayout(self, QLayout): argument 1 has unexpected type 'QGroupBox'
what is the problem?

The problem is exactly what the error reports: you're trying to set a layout (which has to be a subclass of QLayout, such as QGridLayout, etc), but the provided argument is a QGroupBox, which is a subclass of QWidget.
If you want to add the QGroupBox to the current widget, you should set a layout for that widget and then add the groupbox to that layout:
def initUI(self):
self.main_layout = QVBoxLayout()
self.setLayout(self.main_layout)
# ...
self.main_layout.addWidget(self.plotview)
If the groupbox is going to be the only "main" widget, there's no need for that, though: you can just subclass from QGroupBox (instead of QWidget):
class LateralMenu(QGroupBox):
# ...
def initUi(self):
self.setTitle("Group of views")
self.text = "Menu Lateral"
self.layout_plotview = QVBoxLayout()
self.setLayout(self.layout_plotview)
self.splitter = QSplitter(Qt.Vertical)
self.First = First()
self.Second = Second()
self.splitter.addWidget(self.First)
self.splitter.addWidget(self.Second)
self.layout_plotview.addWidget(self.splitter)
Note that I've changed some names (most importantly, self.layout has become self.splitter), and that's for clarity: while QSplitter behaves similarly to a layout, it is not a layout, but a QWidget; naming it "layout" might create a lot of confusion.
Also, you should not overwrite existing class properties (such as, indeed, self.layout).
Finally, avoid using capitalized names for variables and attributes: both First and Second instances should be lower case (read more about this in the Style Guide for Python Code).

Related

PySide2 change QLabel text by clicking QPushButton

I'm trying to change QLabel text by clicking QPushbutton.
I installed PySide2==5.15.2.1
Python 3.7.6 32bit in Windows 10 environment.
First, I made UI class (well, I didn't used Qt designer so I don't have *.ui file)
import PySide2.QtWidgets as qtw
...
class UI_MainWindow(object):
def setupUI(self, MainWindow):
window = qtw.QWidget()
someButton = qtw.QPushButton("button")
someLabel = qtw.QLabel("---")
...
MainWindow.setCentralWidget(window)
And there is some other class who has functions and connects as below
import PySide2.QtWidgets as qtw
from uiSomething import UI_MainWindow #uiSomething is a name of the file of the code above, who has UI_MainWindow class.
...
class something(qtw.QMainWindow, UI_MainWindow):
def __init__(self):
super(something, self).__init__()
self.ui = UI_MainWindow()
self.ui.setupUI(self)
self.someButton.clicked.connect(self.function) # not working. ui.someButton... also not working.
#if I put this connect in UI_MainWindow, at least connect works.
def function(self):
self.ui.someLabel.setText("change text") # not working. ui.someLabel...also not working.
and the other file, I put main function
import Something
import PySide2.QtWidgets as qtw
...
if __name__ == "__main__":
app = qtw.QApplication()
MainWindow = Something.something()
MainWindow.show()
app.exec__()
However, it just give me an error message as below when I click the button.
AttributeEror: 'UI_MainWindow' object has no attribute 'someLabel'
I thought it's okay to define every widgets in setupUI function but probably not..?
Please let me know if there is any idea.
Thank you in advance!
Best wishes,
JESuh
Because someButton and someLabel are not declared as class attributes. These variables are only accessible within the function(setupUI). Objects created from UI_MainWidow cannot call or modify them. Not even if you create a subclass of UI_MainWindow.
Change
import PySide2.QtWidgets as qtw
...
class UI_MainWindow(object):
def setupUI(self, MainWindow):
window = qtw.QWidget()
someButton = qtw.QPushButton("button")
someLabel = qtw.QLabel("---")
...
MainWindow.setCentralWidget(window)
To
import PySide2.QtWidgets as qtw
...
class UI_MainWindow(object):
def setupUI(self, MainWindow):
window = qtw.QWidget()
self.someButton = qtw.QPushButton("button")
self.someLabel = qtw.QLabel("---")
...
MainWindow.setCentralWidget(window)
#blaqICE's answer is a good start but I'm noticing a handful of other things that are contributing to your issues.
The main things I'm seeing are your use of class inheritance and instance attributes. Overall organization seems to be working against you as well. The way you're doing it is workable but it gets confusing pretty quickly. I'm not sure how familiar you are with creating classes but I would spend some time in the python classes docs and looking at PySide example code.
If you want to fix your code the way it is all you need to do is fix the lines I commented on:
uiSomething.py
import PySide2.QtWidgets as qtw
class UI_MainWindow(object):
def setupUI(self, MainWindow): # consider using __init__ instead
self.window = qtw.QWidget() # make an instance attribute for later access with your class instance; not needed with __init__ and proper inheritance
self.main_layout = qtw.QVBoxLayout() # create a layout to hold everything
self.window.setLayout(self.main_layout) # set 'self.window' layout to the new 'self.main_layout'
self.someButton = qtw.QPushButton("button") # make an instance attribute for later access with your class instance
self.main_layout.addWidget(self.someButton) # add 'self.someButton' to 'self.main_layout'
self.someLabel = qtw.QLabel("---") # make an instance attribute for later access with your class instance
self.main_layout.addWidget(self.someLabel) # add 'self.someLabel' to 'self.main_layout'
MainWindow.setCentralWidget(self.window)
Something.py
from uiSomething import UI_MainWindow
class something(qtw.QMainWindow, UI_MainWindow):
def __init__(self):
super(something, self).__init__()
self.ui = UI_MainWindow()
self.ui.setupUI(self) # consider using __init__ in class definition instead; this line would not be needed
self.ui.someButton.clicked.connect(self.function) # 'self.ui' before 'someButton' to access instance's someButton
def function(self):
self.ui.someLabel.setText("change text") # this is fine
# this was not working because of the issue with someButton's signal connection
main.py
import Something
import PySide2.QtWidgets as qtw
# import sys
if __name__ == "__main__":
app = qtw.QApplication()
MainWindow = Something.something()
MainWindow.show()
app.exec_() # only one underscore; typically done as 'sys.exit(app.exec_())' to formally exit python interpreter
However, a better implementation would be:
uiSomething.py
import PySide2.QtWidgets as qtw
class UI_MainWidget(qtw.QWidget): # UI_MainWindow -> UI_MainWidget for clarity; inherit QWidget
def __init__(self, button_text="button", lable_click_text="change text", parent=None): # auto initialize object
super(UI_MainWidget, self).__init__(parent) # pass parent to inherited class __init__ function
# 'self.window' no longer needed due to __init__ and can be accessed simply through 'self'
self.parent = parent # set parent as instance variable for later use if needed
self.button_text = button_text # set custom arguments as instance variable for later use if needed
self.lable_click_text = lable_click_text # set custom arguments as instance variable for later use if needed
self.main_layout = qtw.QVBoxLayout() # create a layout to hold everything
self.setLayout(self.main_layout) # set the widget's layout to the new self.main_layout
self.someButton = qtw.QPushButton(self.button_text) # class argument for easy customization of other instances
self.someButton.clicked.connect(self.function) # moved to instantiation class for clarity and ease of access
self.main_layout.addWidget(self.someButton)
self.someLabel = qtw.QLabel("---") # placeholder text
self.main_layout.addWidget(self.someLabel)
# moved '.setCentralWidget(self)' to main window class for organization and ease of access
def function(self): # move to instantiation class for clarity, organization, and ease of access
# 'self.ui' no longer needed in instantiation class, use 'self' instead
self.someLabel.setText(self.lable_click_text) # class argument for easy customization of other instances
Something.py
import PySide2.QtWidgets as qtw # need to import module here as well due to inheritance
from uiSomething import UI_MainWidget
# for this class, double inheritance doesn't really have any effect. Stick with the main one it represents.
class UI_MainWindow(qtw.QMainWindow): # something -> UI_MainWindow for clarity; inherit QMainWindow only; PEP 8 naming
def __init__(self, parent=None): # added parent kwarg for parenting to other widgets if needed
super(UI_MainWindow, self).__init__(parent) # pass parent to inherited class __init__ function
self.ui = UI_MainWidget(parent=self)
# self.ui.setupUI(self) # no longer needed due to __init__; can delete
# using custom class keyword arguments
# self.ui = UI_MainWidget(button_text="new button name", lable_click_text="new button clicked", parent=self)
# self.ui = UI_MainWidget(button_text="another button name", lable_click_text="another button clicked", parent=self)
self.setCentralWidget(self.ui)
main.py
import Something
import PySide2.QtWidgets as qtw
import sys
if __name__ == "__main__":
app = qtw.QApplication()
MainWindow = Something.UI_MainWindow()
MainWindow.show()
sys.exit(app.exec_())

PyQt5- Add Custom QComboBox to Pop up Window

I have created a custom class inherited from QCombobox() as part of my main application which works fine. I now want to add the same widget to another window upon clicking the ChangeAttributesButton() (QPushButton()). Relevant snippets of code below.
import sys, os, glob
from PyQt5.QtWidgets import (QApplication, QLabel, QMdiSubWindow,
QMainWindow, QAction, QPushButton, QFileDialog, QComboBox)
from PyQt5.QtCore import Qt, pyqtSignal, QObject
from qgis.core import *
from qgis.gui import *
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# Save reference to the QGIS interface
self.iface = iface
self.canvas = self.iface.mapCanvas()
self.project = QgsProject.instance()
self.setWindowTitle('Marker')
#add toolbar
self.toolbar = QToolBar("Grade Marker Toolbar")
self.toolbar.setIconSize(QSize(20,20))
self.addToolBar(self.toolbar)
self.SelectCategoryComboBox = SelectCategoryComboBox()
self.toolbar.addWidget(self.SelectCategoryComboBox)
self.toolbar.addSeparator()
self.ChangeAttributesButton = ChangeAttributesButton(self.canvas)
self.ChangeAttributesButton.setIcon(QIcon(r'abc.png'))
self.ChangeAttributesButton.setIconText('Change Grade')
self.toolbar.addWidget(self.ChangeAttributesButton)
self.toolbar.addSeparator()
self.ChangeAttributesButton.clicked.connect(self.ChangeAttributesButton.on_click)
class SelectCategoryComboBox(QComboBox):
def __init__(self):
super(SelectCategoryComboBox, self).__init__()
self.setEnabled(True)
categories = ['Select Category',"A+","A", "B", "C", "F" ]
for cat in categories:
self.addItem(cat)
The bit that is causing a problem is here:
class ChangeAttributesButton(QPushButton):
def __init__(self,canvas):
super(ChangeAttributesButton, self).__init__()
self.setEnabled(True)
self.canvas = canvas
def on_click(self,state):
window = ChangeAttributesWindow()
class ChangeAttributesWindow(QWidget):
def __init__(self):
super(ChangeAttributesWindow, self).__init__()
self.title = 'Change Feature Attributes'
category_box = SelectCategoryComboBox()
self.addWidget(category_box)
self.initUI()
def initUI(self):
self.show()
app = QApplication(sys.argv)
window = MainWindow()
window.show()
I am getting
AttributeError: 'ChangeAttributesWindow' object has no attribute 'addWidget'`. I have tried changing the parent class of `ChangeAttributesWindow()
to
QMdiSubWindow()
and QMainWindow() but I still get an error in the same vein.
How do I add an instance of SelectCategoryComboBox() to a child or pop up window?
This is the complete error:
A QWidget does not have any method called addWidget() so this error is thrown.
If you want to add a widget to a window, you can add it:
Setting the parent of the widget to the window.
class ChangeAttributesWindow(QWidget):
def __init__(self):
super(ChangeAttributesWindow, self).__init__()
self.title = 'Change Feature Attributes'
category_box = SelectCategoryComboBox()
category_box.setParent(self)
category_box.move(30, 30)
self.initUI()
Use a layout established in the window.
class ChangeAttributesWindow(QWidget):
def __init__(self):
super(ChangeAttributesWindow, self).__init__()
self.title = 'Change Feature Attributes'
category_box = SelectCategoryComboBox()
lay = QVBoxLayout(self)
lay.addWidget(category_box)
self.initUI()

Why doesn't this custom QWidget display correctly

I'm retrying this question with a much better code example.
The code below, in its current form, will display a green shaded QWidget in a window, which is what I want. However, when commenting out the line:
self.widget = QWidget(self.centralwidget)
and uncommenting,
self.widget = Widget_1(self.centralwidget)
the green box doesn't display. The Widget_1 class is a simple subclass of QWidget, so I'm trying to wrap my head around where the breakdown is occurring. There are no error messages, and the print("Test") line within the Widget_1 class is outputting just fine, so I know everything is being called properly.
I'm not looking to use any type of automated layouts for reasons I don't need to go into here. Can you help me to understand why the green rectangle isn't displaying, and what correction I would need to make in order to utilize the Widget_1 class?
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtCore import QRect
import sys
class Main_Window(object):
def setupUi(self, seating_main_window):
seating_main_window.setObjectName("seating_main_window")
seating_main_window.setEnabled(True)
seating_main_window.resize(400, 400)
self.centralwidget = QWidget(seating_main_window)
self.centralwidget.setObjectName("centralwidget")
########### The following two lines of code are causing the confusion #######
# The following line, when uncommented, creates a shaded green box in a window
self.widget = QWidget(self.centralwidget) # Working line
# The next line does NOT create the same shaded green box. Where is it breaking?
# self.widget = Widget_1(self.centralwidget) # Non-working line
self.widget.setGeometry(QRect(15, 150, 60, 75))
self.widget.setAutoFillBackground(False)
self.widget.setStyleSheet("background: rgb(170, 255, 0)")
self.widget.setObjectName("Widget1")
seating_main_window.setCentralWidget(self.centralwidget)
class Widget_1(QWidget):
def __init__(self, parent=None):
super().__init__()
self.setMinimumSize(10, 30) # I put this in thinking maybe I just couldn't see it
print("Test") # I see this output when run when Widget_1 is used above
class DemoApp(QMainWindow, Main_Window):
def __init__(self):
super().__init__()
self.setupUi(self)
if __name__ == '__main__': # if we're running file directly and not importing it
app = QApplication(sys.argv) # A new instance of QApplication
form = DemoApp() # We set the form to be our ExampleApp (design)
form.show() # Show the form
app.exec_() # run the main function
Accoriding to this Qt Wiki article:
How to Change the Background Color of QWidget
you must implement paintEvent in a custom QWidget subclass in order to use stylesheets. Also, since the widget is not part of a layout, you must give it a parent, otherwise it will not be shown. So your Widget_1 class must look like this:
from PyQt5.QtWidgets import QStyleOption, QStyle
from PyQt5.QtGui import QPainter
class Widget_1(QWidget):
def __init__(self, parent=None):
super().__init__(parent) # set the parent
print("Test")
def paintEvent(self, event):
option = QStyleOption()
option.initFrom(self)
painter = QPainter(self)
self.style().drawPrimitive(QStyle.PE_Widget, option, painter, self)
super().paintEvent(event)

QMainWindow vs QWidget

I can't find good explanations about the different usage of QMainWindow vs. QWidget in PyQt5 (and Qt in general, I guess). From what I've read, QMainWindow inherits from QWidget, so should be able to do everything QWidget can and more. But when I try to convert an example I've found from QWidget into QMainWindow, the layout gets screwed up.
The example I'm trying to work off is from https://www.tutorialspoint.com/pyqt/pyqt_qstackedwidget.htm. (My GUI will have a StackedWidget as central widget, with a sidepanel for navigation, so getting this example to work in a QMainWidget would be a great basis for my own code.)
PyQT5-converted and slightly shortened version:
#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import (QApplication, QFormLayout, QLabel, QRadioButton, QCheckBox,
QListWidget, QStackedWidget, QLineEdit,
QHBoxLayout, QGridLayout
)
from PyQt5.Qt import QWidget, QMainWindow
class StackedExample(QMainWindow):
def __init__(self):
super(stackedExample, self).__init__()
self.leftlist = QListWidget ()
self.leftlist.insertItem (0, 'Contact' )
self.leftlist.insertItem (1, 'Personal' )
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack1UI()
self.stack2UI()
self.Stack = QStackedWidget (self)
self.Stack.addWidget (self.stack1)
self.Stack.addWidget (self.stack2)
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(self.leftlist,0,0)
grid.addWidget(self.Stack,0,1)
self.leftlist.currentRowChanged.connect(self.display)
self.resize(300,100)
self.show()
def stack1UI(self):
layout = QFormLayout()
layout.addRow("Name",QLineEdit())
layout.addRow("Address",QLineEdit())
self.stack1.setLayout(layout)
def stack2UI(self):
layout = QFormLayout()
sex = QHBoxLayout()
sex.addWidget(QRadioButton("Male"))
sex.addWidget(QRadioButton("Female"))
layout.addRow(QLabel("Sex"),sex)
layout.addRow("Date of Birth",QLineEdit())
self.stack2.setLayout(layout)
def display(self,i):
self.Stack.setCurrentIndex(i)
def main():
app = QApplication(sys.argv)
ex = StackedExample()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This code worked fine while it was based on QWidget, but when it's based on QMainWidget (like in the above version), everything gets crammed into the upper left corner.
What changes are neccessary to show a layout that works for QWidget in a QMainWindow?
A QMainWindow must have a central widget to display correctly. You need to define a central widget and then add any layouts to it instead of the main window.
class StackedExample(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.leftlist = QListWidget()
self.leftlist.insertItem(0, 'Contact' )
self.leftlist.insertItem(1, 'Personal' )
self.central_widget = QWidget() # define central widget
self.setCentralWidget(self.central_widget) # set QMainWindow.centralWidget
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack1UI()
self.stack2UI()
self.Stack = QStackedWidget (self)
self.Stack.addWidget (self.stack1)
self.Stack.addWidget (self.stack2)
grid = QGridLayout()
self.centralWidget().setLayout(grid) # add the layout to the central widget
grid.addWidget(self.leftlist,0,0)
grid.addWidget(self.Stack,0,1)
self.leftlist.currentRowChanged.connect(self.display)
self.resize(300,100)
self.show()
There are also other areas besides centralWidget defined for a QMainWindow. Here is the documentation for QMainWindow. It explains this in more detail.

QMainWindow flashes and disappears when called from another QMainWindow

This fairly minimal code creates a systray item with three right click options. One is an instance of QDialog, another QMainWindow, and also Quit. It's for a systray-driven app that will have some qdialogs and also a qmainwindow containing a table widget (or, is it possible to create a table into a qdialog?). I've been stuck on this for a week or so, read a lot of related materials and do not understand how to resolve it.
From the systray icon menu, clicking on QDialog, the dialog opens, waits for user action, and clicking the Ok or Cancel buttons will print which one was clicked. It would seem this works because QDialog has its own exec_(). Great so far.
However, clicking on the QMainWindow menu option, the main window dialog appears briefly and disappears with no chance for user input, of course. Maybe instead, the qmainwindow dialog would need to rely on the QApplication's exec_() where the object would instead be initialized just before app.exec_() perhaps? If that would work, I'm not clear on how def qmainwindow() would retrieve the information back from the user.
Hopefully a simple matter for someone who knows, a few changes, bingo.
Current environment: Windows 7 or XP, Python 2.7, Pyside
If you run this, there will be a blank place-holder in the systray that is clickable (right click), or you can also give it an actual image in place of 'sample.png'.
#!python
from PySide import QtGui, QtCore
from PySide.QtGui import QApplication, QDialog, QMainWindow
def qdialog():
qdialog_class_obj = TestClassQDialog()
qdialog_class_obj.show()
qdialog_class_obj.exec_() # wait for user
print "qdialog_user_action: ", qdialog_class_obj.qdialog_user_action
def qmainwindow():
qmainwindow_class_obj = TestClassQMainWindow()
qmainwindow_class_obj.show()
#qmainwindow_class_obj.exec_() # 'TestClassQMainWindow' object has no attribute 'exec_'
class TestClassQDialog(QDialog):
def __init__(self, parent=None):
super(TestClassQDialog, self).__init__(parent)
self.ok_cancel = QtGui.QDialogButtonBox(self)
self.ok_cancel.setStandardButtons(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel)
QtCore.QObject.connect(self.ok_cancel, QtCore.SIGNAL("accepted()"), self.button_ok)
QtCore.QObject.connect(self.ok_cancel, QtCore.SIGNAL("rejected()"), self.button_cancel)
def button_ok(self):
self.qdialog_user_action = 'ok'
self.hide()
def button_cancel(self):
self.qdialog_user_action = 'cancel'
self.hide()
class TestClassQMainWindow(QMainWindow):
def __init__(self, parent=None):
super(TestClassQMainWindow, self).__init__(parent)
self.ok_cancel = QtGui.QDialogButtonBox(self)
self.ok_cancel.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
QtCore.QObject.connect(self.ok_cancel, QtCore.SIGNAL("accepted()"), self.button_ok)
QtCore.QObject.connect(self.ok_cancel, QtCore.SIGNAL("rejected()"), self.button_cancel)
def button_ok(self):
self.hide()
def button_cancel(self):
self.hide()
class SysTrayIcon(QMainWindow):
def __init__(self, parent=None):
super(SysTrayIcon, self).__init__(parent)
self.qdialog_action = QtGui.QAction("QDialog", self, triggered=qdialog)
self.qmainwindow_action = QtGui.QAction("QMainWindow", self, triggered=qmainwindow)
self.quit_action = QtGui.QAction("Quit", self, triggered=QtGui.qApp.quit)
self.createSystrayIcon()
self.systrayIcon.show()
def createSystrayIcon(self):
self.systrayIconMenu = QtGui.QMenu(self)
self.systrayIconMenu.addAction(self.qdialog_action)
self.systrayIconMenu.addAction(self.qmainwindow_action)
self.systrayIconMenu.addSeparator()
self.systrayIconMenu.addAction(self.quit_action)
self.systrayIcon = QtGui.QSystemTrayIcon(self)
self.systrayIcon.setContextMenu(self.systrayIconMenu)
self.systrayIcon.setIcon(QtGui.QIcon('sample.png')) # point to a valid image if you want.
self.systrayIcon.setVisible(True)
if __name__ == '__main__':
app = QtGui.QApplication([])
systrayicon = SysTrayIcon()
app.exec_()
I've got it working. What I did was move your external method qmainwindow inside of your
SysTrayIcon and created the class parameter self.qmainwindow_class_obj = TestClassQMainWindow(). I've attached the working code below. Also, you're using the old style signal slot method, I take it you're coming from old school PyQt. The new method if very nice, clean and pythonic. I've also put the new style methods in the below code. Another thing I would do is move your qdialog method inside the SysTrayIcon class. I don't really understand why you have it outside the class but maybe I'm missing something. Hope this helps.
#!python
from PySide import QtGui, QtCore
from PySide.QtGui import QApplication, QDialog, QMainWindow
def qdialog():
qdialog_class_obj = TestClassQDialog()
qdialog_class_obj.show()
qdialog_class_obj.exec_() # wait for user
print "qdialog_user_action: ", qdialog_class_obj.qdialog_user_action
class TestClassQDialog(QDialog):
def __init__(self, parent=None):
super(TestClassQDialog, self).__init__(parent)
self.ok_cancel = QtGui.QDialogButtonBox(self)
self.ok_cancel.setStandardButtons(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel)
self.ok_cancel.accepted.connect(self.button_ok)
self.ok_cancel.rejected.connect(self.button_cancel)
def button_ok(self):
self.qdialog_user_action = 'ok'
self.hide()
def button_cancel(self):
self.qdialog_user_action = 'cancel'
self.hide()
class TestClassQMainWindow(QMainWindow):
def __init__(self, parent=None):
super(TestClassQMainWindow, self).__init__(parent)
self.ok_cancel = QtGui.QDialogButtonBox(self)
self.ok_cancel.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.ok_cancel.accepted.connect(self.button_ok)
self.ok_cancel.rejected.connect(self.button_cancel)
def button_ok(self):
self.hide()
def button_cancel(self):
self.hide()
class SysTrayIcon(QMainWindow):
def __init__(self, parent=None):
super(SysTrayIcon, self).__init__(parent)
self.qmainwindow_class_obj = TestClassQMainWindow()
self.qdialog_action = QtGui.QAction("QDialog", self, triggered=qdialog)
self.qmainwindow_action = QtGui.QAction("QMainWindow", self, triggered=self.qmainwindow)
self.quit_action = QtGui.QAction("Quit", self, triggered=QtGui.qApp.quit)
self.createSystrayIcon()
self.systrayIcon.show()
def createSystrayIcon(self):
self.systrayIconMenu = QtGui.QMenu(self)
self.systrayIconMenu.addAction(self.qdialog_action)
self.systrayIconMenu.addAction(self.qmainwindow_action)
self.systrayIconMenu.addSeparator()
self.systrayIconMenu.addAction(self.quit_action)
self.systrayIcon = QtGui.QSystemTrayIcon(self)
self.systrayIcon.setContextMenu(self.systrayIconMenu)
self.systrayIcon.setIcon(QtGui.QIcon('linux.jpeg')) # point to a valid image if you want.
self.systrayIcon.setVisible(True)
def qmainwindow(self):
self.qmainwindow_class_obj.show()
if __name__ == '__main__':
app = QtGui.QApplication([])
systrayicon = SysTrayIcon()
app.exec_()

Resources