Issue
I have several plots that I want the user to evaluate with OK/NOK. How do I group all the OKs and NOKs such that when any of the OKs is pressed, the button turns green (or red when NOK is pressed). At the moment I have it for one button only.
x_mean_ok = QPushButton("OK")
x_mean_ok.setCheckable(True)
x_mean_ok.setStyleSheet(":checked{ background-color: #6cdb53;}")
Also, when the user clicks OK and then NOK in the same plot then the OK button should "get" unselected again, so another grouping is needed. I assume I need QGroupBox
for the latter but not quite sure how to put it all together. Here is a visual to get a better idea:
Buttons:
I'm new to pyqt so the question probably has a trivial answer, I just don't seem to find it.
Solution
QGroupBox is only a visual container, it has nothing to do with the relation between buttons.
Well, almost: when adding radio buttons to the same parent (no matter if it's a QGroupBox, a QFrame, a plain QWidget, etc), they become automatically exclusive, since their autoExclusive property is enabled for QRadioButton, but that's not your case: even if you were setting the property for those buttons, you seem to need a state for which also no button could be checked, and exclusiveness doesn't allow that.
The simplest solution would be to create a function that returns the widgets grouped by a parent, with all the parameters and basic functions set:
def createButtons(self):
def check_ok(state):
if state:
x_mean_ok.setChecked(False)
x_mean_ok = QPushButton("OK")
x_mean_ok.setCheckable(True)
x_mean_ok.setStyleSheet(":checked{ background-color: #6cdb53;}")
x_mean_nok = QPushButton("NOK")
x_mean_nok.setCheckable(True)
x_mean_nok.setStyleSheet(":checked{ background-color: red;}")
x_mean_nok.toggled.connect(check_ok)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(x_mean_ok)
layout.addWidget(x_mean_nok)
return layout, x_mean_ok, x_mean_nok
# ...
def somefunction(self):
# create the plot...
button_layout, x_mean_ok, x_mean_nok = self.createButtons()
layout.addLayout(button_layout)
# ...
Some considerations:
To logically group buttons, you can use the QButtonGroup class.
If you're adding many objects and plots, I'd suggest you to use a subclass for each group, and add a new instances everytime; this will make your code more cleaner and better organized.
stylesheets support the property selector to differentiate widgets. You can set a property for those buttons and set a single stylesheet for the parent (or even the whole QApplication):
def createButtons(self): x_mean_ok.setProperty("OK", True) x_mean_nok.setProperty("NOK", True) # ... app = QApplication(sys.argv) app.setStyleSheet(''' QPushButton[OK="true"]:checked { background-color: #6cdb53; } QPushButton[NOK="true"]:checked { background-color: red; } ''')
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.