How to get the checked radiobutton from a groupbox in pyqt - pyqt4

I have a groupbox with some radiobuttons. How do I get to know which one which is checked.

Another way is to use button groups. For example:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MoodExample(QGroupBox):
def __init__(self):
super(MoodExample, self).__init__()
# Create an array of radio buttons
moods = [QRadioButton("Happy"), QRadioButton("Sad"), QRadioButton("Angry")]
# Set a radio button to be checked by default
moods[0].setChecked(True)
# Radio buttons usually are in a vertical layout
button_layout = QVBoxLayout()
# Create a button group for radio buttons
self.mood_button_group = QButtonGroup()
for i in xrange(len(moods)):
# Add each radio button to the button layout
button_layout.addWidget(moods[i])
# Add each radio button to the button group & give it an ID of i
self.mood_button_group.addButton(moods[i], i)
# Connect each radio button to a method to run when it's clicked
self.connect(moods[i], SIGNAL("clicked()"), self.radio_button_clicked)
# Set the layout of the group box to the button layout
self.setLayout(button_layout)
#Print out the ID & text of the checked radio button
def radio_button_clicked(self):
print(self.mood_button_group.checkedId())
print(self.mood_button_group.checkedButton().text())
app = QApplication(sys.argv)
mood_example = MoodExample()
mood_example.show()
sys.exit(app.exec_())
I found more information at:
http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?index=387&key=QButtonGroupClick
http://www.pythonschool.net/pyqt/radio-button-widget/

you will need to iterate through all the radio buttons in the groupbox and check for the property isChecked() of each radiobox.
eg:
radio1 = QtGui.QRadioButton("button 1")
radio2 = QtGui.QRadioButton("button 2")
radio3 = QtGui.QRadioButton("button 3")
for i in range(1,4):
buttonname = "radio" + str(i)
if buttonname.isChecked():
print buttonname + "is Checked"
for reference, check http://pyqt.sourceforge.net/Docs/PyQt4/qradiobutton.html

I managed to work around this problem by using a combination of index and loop.
indexOfChecked = [self.ButtonGroup.buttons()[x].isChecked() for x in range(len(self.ButtonGroup.buttons()))].index(True)

def izle(self):
radios=["radio1","radio2","radio3","radio4"]
for i in range(0,4):
selected_radio = self.ui.findChild(QtGui.QRadioButton, self.radios[i])
if selected_radio.isChecked():
print selected_radio.objectName() + "is Checked"

you can get all chaild objects of class from desired parent. something like
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setupUi(self)
self.show()
print(self.getCheckedRbName(self.gbRadioButtonsGroup))
def getCheckedRbName(self, rbParent: QWidget) -> str:
for rb in rbParent.findChildren(QRadioButton):
if rb.isChecked():
return rb.objectName()
gives you
#> 'rbThirdOption' is checked

Related

User defined slot doesn't run after radio button is clicked

I'm having trouble getting a custom slot to work after a radio button in my QGroupBox is clicked. Here's the relevant part of the code (PySide2)
class ChooseTarget(QtWidgets.QGroupBox):
def __init__(self, title=None):
super().__init__(title)
with open(definitions.JSON_PATH) as j_file:
names = json.load(j_file)
self.radios = [QtWidgets.QRadioButton(names['names'][i]) for i in range(11)]
self.radios[names['names'].index(names["lastTarget"])].setChecked(True)
self.layout = QtWidgets.QGridLayout()
self.button = QtWidgets.QPushButton("Ok")
self.styleButton()
self.addToLayout()
def addToLayout(self):
for i in range(11):
#adding radio buttons to grid layout
if i < 4:
self.layout.addWidget(self.radios[i],0,i)
elif i >= 4 and i < 8:
self.layout.addWidget(self.radios[i],1, i - 4)
else:
self.layout.addWidget(self.radios[i],2, i - 8)
self.radios[i].clicked.connect(self.handleClick)
self.layout.addWidget(self.button,2,3)
handleclick for now is just a method with a print, and I verified that it never runs when the radio buttons are clicked. I've tried using the #Slot decorator as well, or the alternative way of connecting sender and receiver with the SIGNAL and SLOT macros.
Edit:
The MainWidget class is the one I show in the main.
class MainWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.mTableOfOils)
self.layout.addWidget(self.text)
self.mRadioButtons = ChooseTarget("Choose the target")
self.layout.addLayout(self.mRadioButtons.layout)
self.setLayout(self.layout)
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MainWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec_())
In the MainWidget class I only added the layout of my QGroupBox but didn't add the radio buttons widget to the main layout, now it works as intended

Overriding QLabel widget in PyQT

I am new to PyQt perhaps thats why facing this issue. I am trying to make a component inserter for excel sheets. For this purpose I am using QT for interface and using Qlabels within parent class of QMainWindow. On the basis of item selected from Qlist Widget, few Qlabels have to change on mainwindow dynamically Component inserter
As can be seen in above picture, the labels like WCAP-; Part Number and all below needs to change dynamically when the selected items change(when select button is clicked). But what happening is if I choose a different item from list, the previous Label stays and the new label is overlapping it as can be seen from picture below showing overlapping of labels
The code below shows that whenever button "Select" is pressed", label2 (Qlabel2) is formed, how can i delete the previous label whenever select button is pressed so that new Label dynamically replaces the old label.
Thanks a lot in advance.
def Display(self):
self.close()
label1 = QtGui.QLabel("Select the sheet",self)
label1.move(0,15)
self.listwidget = QtGui.QListWidget(self)
self.listwidget.move(0,40)
self.listwidget.resize(150,150)
for i in range(len(self.sheetnames)):
self.listwidget.addItem("%s"%self.sheetnames[i])
btn = QtGui.QPushButton('Select',self)
btn.resize(50,50)
btn.move(170,40)
btn.clicked.connect(self.Selected)
self.show()
def Selected(self):
self.close()
selecteditem = self.listwidget.currentItem().text()
self.sheetindex = self.sheetnames.index(selecteditem)
print self.sheetindex
aa = self.loadsheet.sheet_by_name(selecteditem)
global label2
label2 = QtGui.QLabel("",self)
label2.setText(selecteditem)
label2.move(0,190)
self.show()
self.InputParameters(aa)
You see a new QLabel because you create a new one every time you call Selected. I would initiate the UI at the creation of the widget (in the __init__ method):
def __init__(self):
self.label2 = QtGui.QLabel("",self)
And only update the text of the Qlabel when Selected is executed:
def Selected(self):
self.label2.setText(selecteditem)
About reinitializing all labels with an unknown number of labels and removing the old ones, you might want to look at QLabel.setParent(None). I wrote you a little example:
from PyQt4 import QtGui, QtCore
import sys
class test(QtGui.QWidget):
def __init__(self,parent=None):
self.widget=QtGui.QWidget.__init__(self, parent)
# Button to add labels
self.btnAdd = QtGui.QPushButton('Add')
self.btnAdd.connect(self.btnAdd, QtCore.SIGNAL('clicked()'),self.btnAddPressed)
# Button to remove labels
self.btnRemove = QtGui.QPushButton('Remove')
self.btnRemove.connect(self.btnRemove, QtCore.SIGNAL('clicked()'), self.btnRemovePressed)
# List to keep track of labels
self.labels=[]
# Layout
self.hbox = QtGui.QHBoxLayout()
self.hbox.addWidget(self.btnAdd)
self.hbox.addWidget(self.btnRemove)
self.setLayout(self.hbox)
self.show()
def btnAddPressed(self):
"""Adds a new label."""
self.labels.append(QtGui.QLabel("lbl"+str(len(self.labels)+1), self))
self.hbox.addWidget(self.labels[-1])
def btnRemovePressed(self):
"""Removes last label."""
self.labels[-1].setParent(None)
self.labels.pop(-1)
def main():
#Creating application
app = QtGui.QApplication(sys.argv)
main_win = test()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

PyQt - Fixed title for combobox

I want to create a PyQt combobox with a fixed title. More specific this means that I want to have a dropdown menu from which the user can select but the dropdown button is always labeled the same. So for example I want to create an option for the user to specify where the legend of a plot is drawn. The button for this should always be labled "Legend" but when you click on it, it opens a dropdown menu with the placing options such as "upper right", "upper left", "top", etc. Once the user selected an option the legend is updated but the button still sais "Legend".
I have this so far:
self.fnLegendButton = QtGui.QComboBox()
self.fnLegendButton.addItems('Upper right,Lower right,Upper left,Lower left,Top,Disable'.split(','))
self.fnLegendButton.setCurrentIndex(0)
self.fnLegendButton.setToolTip('Select the legend position.')
self.fnLegendButton.currentIndexChanged.connect( <positioning function> )
self.fnLegendButton.setMaximumWidth(60)
Here's a working example:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.fnLegendButton = QtGui.QComboBox(self)
self.fnLegendButton.addItems(
'Legend,Upper right,Lower right,Upper left,Lower left,Top,Disable'.split(','))
self.fnLegendButton.setCurrentIndex(0)
self.fnLegendButton.setToolTip('Select the legend position.')
self.fnLegendButton.currentIndexChanged[
str].connect(self.avoid_db_change)
self.fnLegendButton.setMaximumWidth(100)
self.fnLegendButton.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('QtGui.QCheckBox')
self.show()
def avoid_db_change(self, text):
print("Processing {0} item".format(text))
self.fnLegendButton.blockSignals(True)
self.fnLegendButton.setCurrentIndex(0)
self.fnLegendButton.blockSignals(False)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The important bits of this code are inside the avoid_db_change, that function is the one used to keep the "Legend" text no matter which item you've pressed. Now, you don't want to fire that function again when self.fnLegendButton.setCurrentIndex(0) is executed, so to avoid that, you surround it by a couple of blockSignals methods. Just try to comment the blockSignals methods and you'll understand what this means.

How to interactively add widgets using QAction in Pyside/Pyqt without using layout management?

I'm trying to make a tool window for Maya, in which I can right-click anywhere, and if I click 'add', a rectangle widget shows up at my cursor position.
Now my right-click functionality works. I can also get my cursor position in addPicker() function. But I am having problem with placing newly-created widgets. If I add a layout and add the newly-created widgets to it, they actually show up. However, if I didn't create a layout for those widgets, no matter what position I tested, nothing shows up in my window.
Hopefully someone has some ideas. Thank you all in advance.
A right-click screenshot:
class RightClickMenu(QtGui.QMenu):
def __init__(self, *args, **kwargs):
super(RightClickMenu, self).__init__(*args)
self.parentWidget().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.parentWidget().customContextMenuRequested.connect(self.menuPos)
def menuPos(self, *args):
self.exec_(QtGui.QCursor.pos())
class Ui_window(object):
def setupUi(self, window):
window.setObjectName("window")
window.resize(555, 900)
self.widget_base = QtGui.QWidget()
self.verticalLayout_window = QtGui.QVBoxLayout(window)
self.verticalLayout_window.addWidget(self.widget_base)
self.menu_popup = RightClickMenu(self.widget_base)
self.menu_popup.setObjectName("popupMenu")
self.verticalLayout_widget = QtGui.QVBoxLayout(self.widget_base)
# Action - add picker
addAction = QtGui.QAction('Add Picker', self.widget_base)
addAction.setShortcut('Ctrl+A')
addAction.setStatusTip('Add Picker')
addAction.triggered.connect(self.addPicker)
self.menu_popup.addAction(addAction)
# Action - delete picker
deleteAction = QtGui.QAction('Delete Picker', self.widget_base)
deleteAction.setShortcut('Ctrl+D')
deleteAction.setStatusTip('Delete Picker')
deleteAction.triggered.connect(self.deletePicker)
self.menu_popup.addAction(deleteAction)
def addPicker(self):
cursorPos = QtGui.QCursor.pos()
localPos = self.widget_base.mapFromGlobal(cursorPos)
######################################################################
# how??? below doesn't work.
self.pushButton = QtGui.QPushButton(self.widget_base)
self.pushButton.setGeometry(QtCore.QRect(220, 50, 75, 23))
self.pushButton.setObjectName("pushButton")
def deletePicker(self):
print 'delete'
def run():
import sys
try:
Ui_window.close()
except:
pass
pickerWindow = QtGui.QDialog()
ui = Ui_window()
ui.setupUi(pickerWindow)
pickerWindow.show()
pickerWindow.exec_()
Surprising solution (see this question):
self.pushButton.show()

How to see signals from QWidgets inside dynamically created QTabWidget pages?

EDIT : I've come up with a solution, and it's much more straightforward than I thought. Original code and question at the top. My solution after "The Question" below..
The Example
from PyQt4 import QtGui, QtCore
from example_Ui import Ui_MainWindow
from filler_Ui import Form
class TabFiller(Form):
def __init__(self, parent=None):
Form.__init__(self, parent)
def TabButtonClicked(self):
print("Tab button pressed.")
def LineEditChanged(self):
print("LineEdit contents edited in tab page!")
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
tab_filler = [] # create empty list for tab contents
tab_page = [] # create empty list for tab page
tab_count = 0
def CreateNewTab(self):
tab_title = "New Tab : " + str(self.tab_count)
self.tab_filler.append(TabFiller())
self.tab_filler[self.tab_count].label.setText(tab_title)
self.tab_page.append(self.tab_filler[self.tab_count])
self.tabWidget.addTab(self.tab_page[self.tab_count], tab_title)
self.tab_count += 1
def MainButtonPressed(self):
self.CreateNewTab()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
MainWindow contains a QTabWidget, which is a Button. clicked() signal has been defined in QtDesigner to be sent to the MainButtonPressed() function inside the MainWindow class.
Form widget also created in QTdesigner. Used to fill additional Tab Pages.
This contains a Button widget, and a LineEdit Widget.
The Question
I can't get my head around how I can tell which widget has been clicked or edited in each tab.
I know that each Tab Page is stored in the list called tab_page.
Within the MainWindow class, how would I receive a clicked() or finishedEditing() signal for a given widget in a currently active tab?
A Solution
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtGui
from example_Ui import Ui_MainWindow
from filler_Ui import Form
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
tab_index = 1 # 1 because we already made a default tab in QtDesigner
def LineEditChanged(self):
findWidget = self.tabWidget.widget(self.tabWidget.currentIndex()).findChildren(QtGui.QLineEdit, "lineEdit")
if findWidget[0].isModified() == True:
print("LineEdit contents edited in tab page!")
print("Name of page edited :", "'", self.tabWidget.tabText(self.tabWidget.currentIndex()),"'")
def TabButtonPressed(self):
print("YOU DID IT!")
print("Current Tab Index = ", self.tabWidget.currentIndex())
def CreateNewTab(self, tabNum):
tab_title = "New Tab : " + str(self.tab_index)
self.tabWidget.addTab(Form(), tab_title)
def MainButtonPressed(self):
self.CreateNewTab(self.tab_index)
findWidget = self.tabWidget.widget(self.tab_index).findChildren(QtGui.QPushButton, "tabButton")
findWidget[0].clicked.connect(self.TabButtonPressed)
findWidget = self.tabWidget.widget(self.tab_index).findChildren(QtGui.QLineEdit, "lineEdit")
findWidget[0].editingFinished.connect(self.LineEditChanged)
self.tab_index += 1
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Using this there's no need for storing each tab page object in a list. You basically use the QTabWidget to index your pages, and off you go.
If anyone has a more elegant way than this, please inform ;)
As outlined in my edited question, I did find the solution to this, which is to use the QTabWidget to "index" each dynamically created tab page.
In QtDesigner I created a main window with one QTabWidget and one button thusly;
Here's the object tree for that;
NOTE: I added a signal/slot for the "Click Me!" button in QtDesigner, so that when that button is clicked, the MainButtonPressed function is called.
To fill the tab pages, I also created a Form in QtDesigner, with a button and a QLineEdit widget;
And the object tree for that;
I'll reproduce the code here. NOTE: I've now updated this answer to use findChild rather than findChildren above:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtGui
from example_Ui import Ui_MainWindow
from filler_Ui import Form
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
tab_index = 1 # 1 because we already made a default tab in QtDesigner
def LineEditChanged(self):
findWidget = self.tabWidget.widget(self.tabWidget.currentIndex()).findChild(QtGui.QLineEdit, "lineEdit")
if findWidget.isModified() == True:
print("LineEdit contents edited in tab page!")
print("Name of page edited :", "'", self.tabWidget.tabText(self.tabWidget.currentIndex()),"'")
def TabButtonPressed(self):
print("YOU DID IT!")
print("Current Tab Index = ", self.tabWidget.currentIndex())
def CreateNewTab(self, tabNum):
tab_title = "New Tab : " + str(self.tab_index)
self.tabWidget.addTab(Form(), tab_title)
def MainButtonPressed(self):
self.CreateNewTab(self.tab_index)
findWidget = self.tabWidget.widget(self.tab_index).findChild(QtGui.QPushButton, "tabButton")
findWidget.clicked.connect(self.TabButtonPressed)
findWidget = self.tabWidget.widget(self.tab_index).findChild(QtGui.QLineEdit, "lineEdit")
findWidget.editingFinished.connect(self.LineEditChanged)
self.tab_index += 1
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
When run, pressing the "Click Me!" button on the main tab page creates a new tab, and adds the contents of the "filler" page to it.
The variable tab_index keeps track of how many tabs there are and allows you to reference the contents of each tab.
To find a widget in a tab, you use the findChild function of Qt;
findWidget = self.tabWidget.widget(self.tab_index).findChild(QtGui.QPushButton, "tabButton")
Finding a specific widget is straightforward. You specify the type of widget you're looking for (QtGui.QPushButton) , and the name you assigned it in QtDesigner (tabButton)
In this case the found widget can be referenced by the variable findWidget.
You can then connect signals to function slots as usual;
findWidget.clicked.connect(self.TabButtonPressed)
In this case I used the new-style signal connection method to connect the clicked() signal to a function named TabButtonPressed in my program.
Rinse and repeat for each widget on the Tab Page you wish to do something with.
After that, it really is plain sailing ;)
I hope this information helps others in their GUI endeavours. You can probably use the same technique with the QToolBox widget.

Resources