I made this wizard containing a radio button. When it is clicked, the finish button should return a list of radio buttons that were checked as text!
The input (it's virtual input for readability)
data=[['a','b','c'],['e','f'],['g','f']]
data1 = ['one','two','three']
this is my code
from PyQt4 import QtGui, QtCore
def page3arg(x, n):
page = QtGui.QWizardPage()
page.setTitle("{}".format(x))
page.setSubTitle("Please choose one of these state.")
rd1 = QtGui.QRadioButton(page)
rd2 = QtGui.QRadioButton(page)
rd3 = QtGui.QRadioButton(page)
layout = QtGui.QGridLayout()
layout.addWidget(rd1, 2, 0)
layout.addWidget(rd2, 2, 1)
layout.addWidget(rd3, 2, 2)
rd1.setText(' {}'.format(n[0]))
rd2.setText(' {}'.format(n[1]))
rd3.setText(' {}'.format(n[2]))
page.setLayout(layout)
return page
def page2arg(x, n):
page = QtGui.QWizardPage()
page.setTitle("{}".format(x))
page.setSubTitle("Please choose one of these state.")
rd1 = QtGui.QRadioButton(page)
rd2 = QtGui.QRadioButton(page)
layout = QtGui.QGridLayout()
layout.addWidget(rd1, 2, 0)
layout.addWidget(rd2, 2, 1)
rd1.setText(' {}'.format(n[0]))
rd2.setText(' {} .'.format(n[1]))
page.setLayout(layout)
return page
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
wizard = QtGui.QWizard()
wizard.setStyleSheet(("font:50 10pt \"MS Shell Dlg 2\";"))
for m in range(len(data1) - 1):
x = data1[m]
n= data[m]
if len(n) == 3:
page3 = page3arg(x, n)
wizard.addPage(page3)
elif len(n) == 2:
page2 = page2arg(x, n)
wizard.addPage(page2)
wizard.show()
sys.exit(wizard.exec_())
How do I write a function that will get the selections of the radio buttons in the end as list.
The list of radio button selections should look like this:
output = ['a','e','g']
If you want to get radiobutton checked, then a simple solution is to associate it with a QButtonGroup for each page and use the checkedButton() function to get the option checked. And to know when you press the finish button you must use the button() function of QWizard and connect it to a slot.
Also it is not necessary to have 2 functions that do the same as page3arg and page2arg, I have reduced it in a generalized function for n arguments
from PyQt4 import QtCore, QtGui
class Wizard(QtGui.QWizard):
def __init__(self, parent=None):
super(Wizard, self).__init__(parent)
datas = [["a", "b", "c"], ["e", "f"], ["g", "f"]]
titles = ["one", "two", "three"]
self.setStyleSheet(('font:50 10pt "MS Shell Dlg 2";'))
self.groups = []
for title, options in zip(titles, datas):
page, group = Wizard.create_page(title, options)
self.addPage(page)
self.groups.append(group)
self.button(QtGui.QWizard.FinishButton).clicked.connect(
self.on_finished
)
self._results = []
#property
def results(self):
self.get_options()
return self._results
def get_options(self):
self._results = []
for group in self.groups:
button = group.checkedButton()
if button is not None:
self._results.append(button.text())
#QtCore.pyqtSlot()
def on_finished(self):
print("finished", self.results)
#staticmethod
def create_page(title, options):
page = QtGui.QWizardPage()
group = QtGui.QButtonGroup(page)
page.setTitle(title)
page.setSubTitle("Please choose one of these state.")
hlay = QtGui.QHBoxLayout(page)
for option in options:
radiobutton = QtGui.QRadioButton(text=option)
group.addButton(radiobutton)
hlay.addWidget(radiobutton)
return page, group
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
wizard = Wizard()
wizard.show()
ret = app.exec_()
print("outside clas", wizard.results)
sys.exit(ret)
Try to put all radio buttons in a list, and for each radio button in the list, get it's text and insert it to your output list.
For example,
lst = []
lst.append(rd1)
lst.append(rd2)
lst.append(rd3)
output = []
for val in lst:
output.append(val.text())
Related
Within my QApplication I want to create QListWidgets dynamically and do something with listitems.
I want to create a Favorite Tab. The only think that work is self.listWidget_fav.clear
There are 4 QPushButtons
the self.buttonOK button have to use the list items
the self.buttonRemoveFav has to remove the entire QListWidget with the 4 QPushButtons
the self.buttonDel has to clear the entire list <---- working
the self.buttonDelSel has to remove selected listItem.
What's wrong?
import sys, time, names
from PyQt5 import QtCore
from PyQt5.QtCore import QAbstractTableModel, Qt
from PyQt5.QtWidgets import *
from functools import partial
import names
colPos = 0
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.resize(800, 600)
self.tabs = QTabWidget()
self.tabs.layout = QGridLayout()
self.tabs.setLayout(self.tabs.layout)
self.grid = QGridLayout()
self.grid.addWidget(self.tabs)
self.setLayout(self.grid)
self.setCentralWidget(self.tabs)
self.result = QTabWidget()
self.result.layout = QGridLayout()
self.result.setLayout(self.result.layout)
self.fav = QTabWidget()
self.fav.layout = QGridLayout()
self.fav.setLayout(self.fav.layout)
self.tabs.addTab(self.result, 'Tab 1')
self.tabs.addTab(self.fav, 'Fav')
#create space to put the export button in the bottom of the TableView
positions = [(i,j) for i in range(20) for j in range(10)]
lst = []
for i in range(30):
lst.append(names.get_full_name())
print(lst)
self.checkBoxes = []
for position, no in zip(positions, lst):
self.checkB = QCheckBox(str(no), self)
self.result.layout.addWidget(self.checkB, *position)
self.checkBoxes.append(self.checkB)
#select All
self.buttonSelAll = QPushButton("Select All", self)
self.buttonSelAll.clicked.connect(partial(self.selectBoxes, True))
self.result.layout.addWidget(self.buttonSelAll, 21, 0)
#select All
self.buttonNone = QPushButton("Select None", self)
self.buttonNone.clicked.connect(partial(self.selectBoxes, False))
self.result.layout.addWidget(self.buttonNone, 21, 1)
#select All
self.buttonFav = QPushButton("Fav", self)
self.buttonFav.clicked.connect(self.toFav)
self.result.layout.addWidget(self.buttonFav, 21, 3)
self.checkBtext = [] # var for text of checkboxes.
for i in range(len(self.checkBoxes)):
self.checkBtext.append(self.checkBoxes[i].text())
self.res = {}
def resetColPos(self):
global colPos
colPos = colPos - 2
self.listWidget_fav.hide()
self.buttonOK.hide()
self.buttonDel.hide()
self.buttonDelSel.hide()
self.buttonRemoveFav.hide()
def removeSelfromFav(self):
listItems = self.listWidget_fav.selectedItems()
if not listItems: return
for item in listItems:
self.listWidget_fav.takeItem(self.listWidget_fav.row(item))
def toFav(self):
global colPos
states = [c.isChecked() for c in self.checkBoxes]
self.selectedChecktext = [] #Text of selected checkbox
for key in self.checkBtext:
for value in states:
self.res[key] = value
states.remove(value)
break
print("self.res.items(): ", self.res.items())
print(len(self.res))
for k, v in self.res.items():
if v == True and not k in self.selectedChecktext:
self.selectedChecktext.append(k)
elif v == False and k in self.selectedChecktext:
self.selectedChecktext.remove(k)
print("self.selectedChecktext: ", self.selectedChecktext)
self.listWidget_fav = QListWidget()
self.listWidget_fav.addItems(self.selectedChecktext)
self.fav.layout.addWidget(self.listWidget_fav, 0, colPos, 5, 2)
self.fav.setLayout(self.fav.layout)
self.buttonOK = QPushButton("ok", self)
self.fav.layout.addWidget(self.buttonOK, 6, colPos)
self.fav.setLayout(self.fav.layout)
self.buttonRemoveFav = QPushButton("Remove Fav", self)
self.buttonRemoveFav.clicked.connect(self.resetColPos)
self.fav.layout.addWidget(self.buttonRemoveFav, 6, colPos+1)
self.fav.setLayout(self.fav.layout)
self.buttonDel = QPushButton("Clear List", self)
self.buttonDel.clicked.connect(self.listWidget_fav.clear)
self.fav.layout.addWidget(self.buttonDel, 7, colPos)
self.fav.setLayout(self.fav.layout)
self.buttonDelSel = QPushButton("Delete selected", self)
self.fav.layout.addWidget(self.buttonDelSel, 7, colPos+1)
self.fav.setLayout(self.fav.layout)
colPos = colPos + 2
def checkStates(self):
states = [c.isChecked() for c in self.checkBoxes]
print ("states: ", states)
def selectBoxes(self, state):
for check in self.checkBoxes:
check.blockSignals(True)
check.setChecked(state)
check.blockSignals(False)
self.checkStates()
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle('Fusion')
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
names Package have to be installed via pip -m install names ;)
I have a QListWidget with custom widgets. I am seeing an issue where if I do the following:
add two items
Remove the second item
Add another item
then the first item's widget contents disappears until I either resize the window, or add a third item.
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class StagingWidget(QGroupBox):
def __init__(self,parent=None):
#QWidget.__init__(self,parent)
super(StagingWidget,self).__init__()
self.itemWidgets = list()
self.count = 1
self.createUi()
def createUi(self):
self.widget_layout=QVBoxLayout(self)
self.list_widget=QListWidget()
self.setFixedWidth(450)
self.setFixedHeight(600)
self.list_widget.setStyleSheet("QListWidget::item:selected{background:lightblue}")
self.widget_layout.addWidget(self.list_widget)
self.buttonHLayout = QHBoxLayout()
self.add = QPushButton("Add Item")
self.add.clicked.connect(self.addListItem)
self.buttonHLayout.addWidget(self.add)
self.widget_layout.addLayout(self.buttonHLayout)
def addListItem(self):
itemN = QListWidgetItem()
widget = QWidget()
Button1 = QPushButton(str(self.count))
Button2 = QPushButton("Remove")
Button2.clicked.connect(lambda item=itemN:self.removeJob(item))
widgetLayout = QHBoxLayout()
widgetLayout.addWidget(Button1)
widgetLayout.addWidget(Button2)
widget.setLayout(widgetLayout)
itemN.setSizeHint(widget.sizeHint())
self.itemWidgets.append(widget)
self.list_widget.addItem(itemN)
self.list_widget.setItemWidget(itemN, self.itemWidgets[-1])
self.count = self.count + 1
def removeJob(self,item):
print("Removing Job")
row = self.list_widget.indexFromItem(item).row()
self.list_widget.takeItem(row)
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = StagingWidget()
widget.show()
sys.exit(app.exec_())
Example:
Add 1 item:
Add another item:
Remove item 2:
Add another item(You can see widget of item 1 disappear):
Add another item(Widget of item 1 reappears):
This happens every single time I do the above steps.
I'm trying to create a layout where the user can click a combination of buttons, each button's click will add a 1 or a 0 to a certain position in a list which is the actual input I'd like to get out of it.
However, I don't know how to manage a cluster of buttons, there are 48 buttons and managing them all individually is the antithesis of DRY.
Here's an example attempt:
num_buttons = 48
press_list = [None]*len(num_buttons)
button_list = list()
for button in range(num_buttons):
some_btn = QtWidgets.QPushButton(SomeDialog)
some_btn.setGeometry(QtCore.QRect(70, 90, 141, 28))
some_btn.setObjectName("button_%s" % (button,))
some_btn.clicked.connect(self.button_pressed(button))
def button_pressed(self, button_num):
if press_list[button_num] == 1:
press_list[button_num] = 0
else:
press_list[button_num] = 1
(clicks turn buttons blue), is it possible to have a set geometry through the Qt designer and still do something like this, or will I have to calculate the setGeometry positions and add the buttons through the code?
If you want to pass an additional argument to the slots you can use partial as shown below:
import sys
from functools import partial
from PyQt5 import QtWidgets
QSS = """
QToolButton::checked{
background-color: blue
}
"""
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.listA = [0 for _ in range(24)]
self.listB = [0 for _ in range(24)]
lay = QtWidgets.QVBoxLayout(self)
hlay1 = QtWidgets.QHBoxLayout()
hlay2 = QtWidgets.QHBoxLayout()
lay.addLayout(hlay1)
lay.addLayout(hlay2)
for i, val in enumerate(self.listA):
button = QtWidgets.QToolButton()
button.setCheckable(True)
hlay1.addWidget(button)
button.clicked.connect(partial(self.callbackA, i))
button.setStyleSheet(QSS)
for i, val in enumerate(self.listB):
button = QtWidgets.QToolButton()
button.setCheckable(True)
hlay2.addWidget(button)
button.clicked.connect(partial(self.callbackB, i))
button.setStyleSheet(QSS)
def callbackA(self, index, state):
self.listA[index] = 1 if state else 0
print("listA: ")
print(self.listA)
def callbackB(self, index, state):
self.listB[index] = 1 if state else 0
print("listB: ")
print(self.listB)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
I have a simple QTreeWidget :
self.treeWidget = QTreeWidget(self)
col = ("Status", "Name")
self.treeWidget.setColumnCount(2)
self.treeWidget.setHeaderLabels(col)
witch I populate using :
wid = Custom_Widget()
item = QTreeWidgetItem(self.treeWidget)
item.setText(1, "some string")
item.treeWidget().setItemWidget(item, 0, wid)
I can easly acces the text column by using :
root = self.treeWidget.invisibleRootItem()
it = root.child(2) # for example the third item
it.setText(1, "Edited")
what i need is to edit the costum_widget in column 0, so how can i access it or invoke his methods ?
I resolved the issue by keeping a list of all the costum_widgets that i create, my code would be :
from CustomWidgets import Custom_Widget
from PyQt5.QtWidgets import *
import sys
class MyExample(QWidget):
def __init__(self):
super().__init__()
self.treeWidget = QTreeWidget(self)
self.group_wid = [] # my list of widgets
col = ("Status", "Name")
self.treeWidget.setColumnCount(2)
self.treeWidget.setHeaderLabels(col)
self.populate_tree()
self.edit_tree()
self.show()
def populate_tree(self):
for i in range(10):
wid = Custom_Widget()
self.group_wid.append(wid) # each time i instantiate a Custom_Widget i'll add it to my list of widgets
item = QTreeWidgetItem(self.treeWidget)
item.setText(1, "some string")
item.treeWidget().setItemWidget(item, 0, wid)
def edit_tree(self):
root = self.treeWidget.invisibleRootItem()
it = root.child(2) # for example the third item
it.setText(1, "Edited")
self.group_wid[2].my_method() # i can easily edit my widgets that are in the QTreeWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyExample()
app.exec_()
Guess the QtreeWidgetItem only hold a reference to the widgets that are contained.
I have a table, with 4 columns.
Two of this 4 columns are about features. One is Feature, another is subfeature.
in each column, there are comboboxes for all cells.
I can open txt in these cells.
I want to: when I choose cinema for feature, I want to see only name of films in subfeature comboboxes and no every subfeature that I have in my "data"... and when I choose Food in feature, I want to see only types of food in my subfeature comboboxes...
.. I dont know how to do it... there is a way to do it?
Here there is my def to put combobox in table and open the text file into these comboboxes:
def createEd(self, parent, option, index):
if index.column() == POLARITY:
combobox = QComboBox(parent)
combobox.addItems(sorted(index.model().TPolarities))
combobox.setEditable(True)
arquivo = codecs.open("ln2.txt",encoding='utf-8',mode="r")
conTWordsdo = arquivo.readlines()
lista =[]
for i in conTWordsdo:
lista.append(i.replace("\n",""))
combobox.addItems(sorted(lista))
return combobox
elif index.column() == FEATURE:
combobox = QComboBox(parent)
combobox.addItems(sorted(index.model().TFeatures))
combobox.setEditable(True)
arquivo = codecs.open("ln1.txt",encoding='utf-8',mode="r")
conTWordsdo = arquivo.readlines()
lista = []
for i in conTWordsdo:
lista.append(i.replace("\n",""))
combobox.addItems(sorted(lista))
return combobox
elif index.column() == SUBFEATURE:
combobox = QComboBox(parent)
combobox.addItems(sorted(index.model().TSubFeatures))
combobox.setEditable(True)
arquivo = codecs.open("ln3.txt",encoding='utf-8',mode="r")
conTWordsdo = arquivo.readlines()
lista = []
for i in conTWordsdo:
lista.append(i.replace("\n",""))
combobox.addItems(sorted(lista))
return combobox
elif index.column() == SENTENCE:
editor = QLineEdit(parent)
self.connect(editor, SIGNAL("returnPressed()"), self.commitAndCloseEditor)
return editor
else:
return QItemDelegate.createEditor(self, parent, option, index)
You'll be using the currentIndexChanged signal, something like this:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.items = dict(zip(
[ "Parent {0}".format(x)
for x in range(3)
],
[
[ "Child {0} - {1}".format(x, y)
for y in range(3)
]
for x in range(3)
]
))
self.comboBoxChild = QtGui.QComboBox(self)
self.comboBoxParent = QtGui.QComboBox(self)
self.comboBoxParent.addItems(self.items.keys())
self.comboBoxParent.currentIndexChanged[str].connect(self.on_comboBoxParent_currentIndexChanged)
self.comboBoxParent.setCurrentIndex(1)
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.comboBoxParent)
self.layoutVertical.addWidget(self.comboBoxChild)
#QtCore.pyqtSlot(str)
def on_comboBoxParent_currentIndexChanged(self, index):
items = self.items[str(index)]
self.comboBoxChild.clear()
self.comboBoxChild.addItems(items)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
main.resize(222, 111)
sys.exit(app.exec_())