Let's say I have an application with a number of QGroupBoxes like so:
import sys
from PyQt4 import QtGui, QtCore
class Main(QtGui.QWidget):
# pylint: disable=too-many-statements
def __init__(self, main):
super(Main, self).__init__()
self.grid_layout = QtGui.QGridLayout()
self.line_edit = QtGui.QLineEdit()
self.grid_layout.addWidget(self.create_settings_group(), 0, 0, 2, 1)
self.push_button = QtGui.QPushButton("go", self)
self.grid_layout.addWidget(self.create_controls_group(), 0, 1)
self.setLayout(self.grid_layout)
main.setCentralWidget(self)
def create_settings_group(self):
group_box_settings = QtGui.QGroupBox(self)
group_box_settings.setTitle("group1")
grid = QtGui.QGridLayout()
grid.addWidget(self.line_edit, 0, 0)
group_box_settings.setLayout(grid)
return group_box_settings
def create_controls_group(self):
group_box_settings = QtGui.QGroupBox(self)
group_box_settings.setTitle("group2")
grid = QtGui.QGridLayout()
grid.addWidget(self.push_button, 0, 0, 1, 2)
group_box_settings.setLayout(grid)
return group_box_settings
class GUI(QtGui.QMainWindow):
def __init__(self):
super(GUI, self).__init__()
self.ui = Main(self)
self.show()
app = QtGui.QApplication(sys.argv)
ex = GUI()
app.exec_()
When I open my simple application I see that the cursor is blinking in the line edit. But I just want the push button in another group box to be highlighted and to have enter press connected to it? how do I do that? using self.push_button.setFocus() doesn't do anything.
You can try setting the button Default property:
self.push_button.setDefault(True)
self.push_button.setFocus()
You have to set the focus a moment after showing up for it you can use a QTimer::singleShot() or QMetaObject::invokeMethod():
1. QTimer::singleShot()
...
self.push_button = QtGui.QPushButton("go", self)
self.grid_layout.addWidget(self.create_controls_group(), 0, 1)
self.push_button.setDefault(True)
QtCore.QTimer.singleShot(0, self.push_button.setFocus)
2. QMetaObject::invokeMethod()
...
self.push_button = QtGui.QPushButton("go", self)
self.grid_layout.addWidget(self.create_controls_group(), 0, 1)
self.push_button.setDefault(True)
QtCore.QMetaObject.invokeMethod(self.push_button,
"setFocus",
QtCore.Qt.QueuedConnection)
Related
Hello I have this code using python and pyqt5 which allows to display a graphical interface :
import sys
from PyQt5 import QtCore, QtWidgets
class TabPage(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
group = QtWidgets.QGroupBox('Monty Python')
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(group)
grid = QtWidgets.QGridLayout(group)
grid.addWidget(QtWidgets.QLabel('Enter a name:'), 0, 0)
grid.addWidget(QtWidgets.QLabel('Choose a number:'), 0, 1)
grid.addWidget(QtWidgets.QLineEdit(), 1, 0)
grid.addWidget(QtWidgets.QComboBox(), 1, 1)
grid.addWidget(QtWidgets.QPushButton('Click Me!'), 1, 2)
grid.addWidget(QtWidgets.QSpinBox(), 2, 0)
grid.addWidget(QtWidgets.QPushButton('Clear Text'), 2, 2)
grid.addWidget(QtWidgets.QTextEdit(), 3, 0, 1, 3)
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.tabs = QtWidgets.QTabWidget()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
button = QtWidgets.QToolButton()
button.setToolTip('Add New Tab')
button.clicked.connect(self.addNewTab)
button.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_DialogYesButton))
self.tabs.setCornerWidget(button, QtCore.Qt.TopRightCorner)
button1 = QtWidgets.QToolButton()
button1.setToolTip('Remove')
button1.clicked.connect(self.addNewTab)
button1.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_BrowserStop))
self.tabs.setCornerWidget(button1, QtCore.Qt.TopRightCorner)
self.addNewTab()
def addNewTab(self):
text = 'Tab %d' % (self.tabs.count() + 1)
self.tabs.addTab(TabPage(self.tabs), text)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
When I execute my code I get this :
whereas I would like to get something like this :
How can I do to do this ?
Thank you a lot !
QTabWidget::setCornerWidget(QWidget *widget, Qt::Corner corner = Qt::TopRightCorner)
Any previously set corner widget is hidden. https://doc.qt.io/qt-5/qtabwidget.html#setCornerWidget
Try it:
import sys
from PyQt5 import QtCore, QtWidgets
class TabPage(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
group = QtWidgets.QGroupBox('Monty Python')
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(group)
grid = QtWidgets.QGridLayout(group)
grid.addWidget(QtWidgets.QLabel('Enter a name:'), 0, 0)
grid.addWidget(QtWidgets.QLabel('Choose a number:'), 0, 1)
grid.addWidget(QtWidgets.QLineEdit(), 1, 0)
grid.addWidget(QtWidgets.QComboBox(), 1, 1)
grid.addWidget(QtWidgets.QPushButton('Click Me!'), 1, 2)
grid.addWidget(QtWidgets.QSpinBox(), 2, 0)
grid.addWidget(QtWidgets.QPushButton('Clear Text'), 2, 2)
grid.addWidget(QtWidgets.QTextEdit(), 3, 0, 1, 3)
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.tabs = QtWidgets.QTabWidget()
self.tabs.setTabsClosable(True) # +
self.tabs.tabCloseRequested.connect(self.qtabwidget_tabcloserequested) # +
self.tabs.currentChanged.connect(lambda: print(f'currentIndex->{self.tabs.currentIndex()}')) #+
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
button = QtWidgets.QToolButton()
button.setFixedSize(20, 20) # +
button.setToolTip('Add New Tab')
button.clicked.connect(self.addNewTab)
button.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_DialogYesButton))
# self.tabs.setCornerWidget(button, QtCore.Qt.TopRightCorner)
button1 = QtWidgets.QToolButton()
button1.setFixedSize(20, 20) # +
button1.setToolTip('Remove')
button1.clicked.connect(self.removeTab) # removeTab
button1.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_BrowserStop))
# Any previously set corner widget is hidden.
# self.tabs.setCornerWidget(button1, QtCore.Qt.TopRightCorner) #
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
self.widget = QtWidgets.QWidget()
h_layout = QtWidgets.QHBoxLayout(self.widget)
h_layout.setContentsMargins(0, 0, 0, 0)
h_layout.addWidget(button)
h_layout.addWidget(button1)
self.tabs.setCornerWidget(self.widget, QtCore.Qt.TopRightCorner)
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
self.addNewTab()
def addNewTab(self):
text = 'Tab %d' % (self.tabs.count() + 1)
self.tabs.addTab(TabPage(self.tabs), text)
#QtCore.pyqtSlot(int)
def qtabwidget_tabcloserequested(self, index):
# gets the widget
widget = self.tabs.widget(index)
# if the widget exists
if widget:
# removes the widget
widget.deleteLater()
# removes the tab of the QTabWidget
self.tabs.removeTab(index)
def removeTab(self):
print('def removeTab(self): print')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
Since the other answer does not explain the cause of the problem and its code is confusing, I will explain the error in detail.
The error is that there can only be one cornerWidget, if you set a second cornerWidget it will replace the previous one, therefore only one QToolButton is observed. If you want to show several widgets then you have to use a container like a QWidget and place the other widgets there.
# ...
layout.addWidget(self.tabs)
button = QtWidgets.QToolButton()
button.setToolTip("Add New Tab")
button.clicked.connect(self.addNewTab)
button.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_DialogYesButton))
button1 = QtWidgets.QToolButton()
button1.setToolTip("Remove")
button1.clicked.connect(self.addNewTab)
button1.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_BrowserStop))
container = QtWidgets.QWidget()
container.setContentsMargins(0, 0, 0, 0)
lay = QtWidgets.QHBoxLayout(container)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(button)
lay.addWidget(button1)
self.tabs.setCornerWidget(container, QtCore.Qt.TopRightCorner)
self.addNewTab()
I am struggling to add a side menu to my application.
I have a QMainWindow instance to which I was hoping to add a QDrawer object and achieve an effect similar to this sample.
Unfortunately, it seems that PySide2 only provides QMenu, QTooltip and QDialog widgets which inherit from the Popup class, and QDrawer is nowhere to be found. However, using a Drawer tag in a QML file works just fine. Shouldn't it be possible to also create an instance of QDrawer programmatically?
As another try, I tried to load a Drawer instance from a QML file and attach it to my QMainWindow. Unfortunately I can't quite understand what should I specify as parent, what should I wrap it in, what parameters should I use etc. - any advice would be appreciated (although I would much rather create and configure it programatically).
My goal is to create a QMainWindow with a toolbar, central widget and a QDrawer instance as a side navigation menu (such as in this sample). Can you please share some examples or explain what to do?
One possible solution is to implement a Drawer using Qt Widgets, the main feature is to animate the change of width for example using a QXAnimation, the other task is to set the anchors so that it occupies the necessary height. A simple example is the one shown in the following code:
import os
from PySide2 import QtCore, QtGui, QtWidgets
class Drawer(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedWidth(0)
self.setContentsMargins(0, 0, 0, 0)
# self.setFixedWidth(0)
self._maximum_width = 0
self._animation = QtCore.QPropertyAnimation(self, b"width")
self._animation.setStartValue(0)
self._animation.setDuration(1000)
self._animation.valueChanged.connect(self.setFixedWidth)
self.hide()
#property
def maximum_width(self):
return self._maximum_width
#maximum_width.setter
def maximum_width(self, w):
self._maximum_width = w
self._animation.setEndValue(self.maximum_width)
def open(self):
self._animation.setDirection(QtCore.QAbstractAnimation.Forward)
self._animation.start()
self.show()
def close(self):
self._animation.setDirection(QtCore.QAbstractAnimation.Backward)
self._animation.start()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
self.tool_button = QtWidgets.QToolButton(
checkable=True, iconSize=QtCore.QSize(36, 36)
)
content_widget = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
content_widget.setText("Content")
content_widget.setStyleSheet("background-color: green")
lay = QtWidgets.QVBoxLayout(central_widget)
lay.setSpacing(0)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(self.tool_button)
lay.addWidget(content_widget)
self.resize(640, 480)
self.drawer = Drawer(self)
self.drawer.move(0, self.tool_button.sizeHint().height())
self.drawer.maximum_width = 200
self.drawer.raise_()
content_lay = QtWidgets.QVBoxLayout()
content_lay.setContentsMargins(0, 0, 0, 0)
label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
label.setText("Content\nDrawer")
label.setStyleSheet("background-color: red")
content_lay.addWidget(label)
self.drawer.setLayout(content_lay)
self.tool_button.toggled.connect(self.onToggled)
self.onToggled(self.tool_button.isChecked())
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.onCustomContextMenuRequested)
#QtCore.Slot()
def onCustomContextMenuRequested(self):
menu = QtWidgets.QMenu()
quit_action = menu.addAction(self.tr("Close"))
action = menu.exec_(QtGui.QCursor.pos())
if action == quit_action:
self.close()
#QtCore.Slot(bool)
def onToggled(self, checked):
if checked:
self.tool_button.setIcon(
self.style().standardIcon(QtWidgets.QStyle.SP_MediaStop)
)
self.drawer.open()
else:
self.tool_button.setIcon(
self.style().standardIcon(QtWidgets.QStyle.SP_MediaPlay)
)
self.drawer.close()
def resizeEvent(self, event):
self.drawer.setFixedHeight(self.height() - self.drawer.pos().y())
super().resizeEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I am trying to make a GUI with PyQt5. It will have a notification button with an icon. I want to add a small bubble with the number of notifications on the icon.
If a number is not possible, I would like to use a red dot as a backup method.
But how should I keep track of the new notifications (like a listener for notification) and change the icon while the window is running?
I have been googling about this problem, but only mobile development stuff and non-PyQt5 related results come up.
Expected result: Let's say we have a list. And the icon of the button will automatically change when a new item is added to the list. Then when the button is clicked, the icon will change back.
A possible solution is to create a widget that has a layout where you place a QToolButton and at the top right a QLabel with a QPixmap that has the number
from PyQt5 import QtCore, QtGui, QtWidgets
def create_pixmap(point, radius=64):
rect = QtCore.QRect(QtCore.QPoint(), 2 * radius * QtCore.QSize(1, 1))
pixmap = QtGui.QPixmap(rect.size())
rect.adjust(1, 1, -1, -1)
pixmap.fill(QtCore.Qt.transparent)
painter = QtGui.QPainter(pixmap)
painter.setRenderHints(
QtGui.QPainter.Antialiasing | QtGui.QPainter.TextAntialiasing
)
pen = painter.pen()
painter.setPen(QtCore.Qt.NoPen)
gradient = QtGui.QLinearGradient()
gradient.setColorAt(1, QtGui.QColor("#FD6684"))
gradient.setColorAt(0, QtGui.QColor("#E0253F"))
gradient.setStart(0, rect.height())
gradient.setFinalStop(0, 0)
painter.setBrush(QtGui.QBrush(gradient))
painter.drawEllipse(rect)
painter.setPen(pen)
painter.drawText(rect, QtCore.Qt.AlignCenter, str(point))
painter.end()
return pixmap
class NotificationButton(QtWidgets.QWidget):
scoreChanged = QtCore.pyqtSignal(int)
def __init__(self, score=0, icon=QtGui.QIcon(), radius=12, parent=None):
super(NotificationButton, self).__init__(parent)
self.m_score = score
self.m_radius = radius
self.setContentsMargins(0, self.m_radius, self.m_radius, 0)
self.m_button = QtWidgets.QToolButton(clicked=self.clear)
self.m_button.setContentsMargins(0, 0, 0, 0)
self.m_button.setIcon(icon)
self.m_button.setIconSize(QtCore.QSize(18, 18))
lay = QtWidgets.QVBoxLayout(self)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(self.m_button)
self.m_label = QtWidgets.QLabel(self)
self.m_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
self.m_label.raise_()
self.setSizePolicy(self.m_button.sizePolicy())
self.update_notification()
#QtCore.pyqtProperty(int, notify=scoreChanged)
def score(self):
return self.m_score
#score.setter
def score(self, score):
if self.m_score != score:
self.m_score = score
self.update_notification()
self.scoreChanged.emit(score)
#QtCore.pyqtSlot()
def clear(self):
self.score = 0
#QtCore.pyqtProperty(int)
def radius(self):
return self.m_radius
#radius.setter
def radius(self, radius):
self.m_radius = radius
self.update_notification()
def update_notification(self):
self.setContentsMargins(0, self.m_radius, self.m_radius, 0)
self.m_label.setPixmap(create_pixmap(self.m_score, self.m_radius))
self.m_label.adjustSize()
def resizeEvent(self, event):
self.m_label.move(self.width() - self.m_label.width(), 0)
super(NotificationButton, self).resizeEvent(event)
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.m_item_le = QtWidgets.QLineEdit("Stack Overflow")
add_button = QtWidgets.QPushButton("Add", clicked=self.add_item)
self.m_notification_button = NotificationButton(
icon=QtGui.QIcon("image.png")
)
self.m_list_widget = QtWidgets.QListWidget()
vlay = QtWidgets.QVBoxLayout(self)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(self.m_item_le)
hlay.addWidget(add_button)
vlay.addLayout(hlay)
vlay.addWidget(
self.m_notification_button, alignment=QtCore.Qt.AlignRight
)
vlay.addWidget(self.m_list_widget)
#QtCore.pyqtSlot()
def add_item(self):
text = self.m_item_le.text()
self.m_list_widget.addItem(
"%s: %s" % (self.m_list_widget.count(), text)
)
self.m_notification_button.score += 1
self.m_list_widget.scrollToBottom()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
It would be nice if you show your code so far. Anyhow, these may help you solve your question:
You'll need two different icons: one to represent a dirty (just loaded) list and the other for the "clean" list
class YourClass(Dialog):
def __init__(self)
super().__init__()
self.lst = []
# ...
def setUI(self):
# ...
self.notButton = QPushButton(icon_off, '0')
self.notButton.clicked.connect(self.clearButton)
# ...
#pyqtSlot()
def clearButton(self):
self.notButton.setIcon(icon_clean)
def addToList(self, item):
self.lst.append(item)
self.notButton.setIcon(icon_dirty)
self.notButton.setText(str(len(self.lst)
A possible solution to updating the icon would be to have a separate image file for each icon and its associated notification number. You can keep track of the number of current notifications in a counter variable. Use that number to call the corresponding icon.
My QGraphicsView should show an image of a large resolution. The size should fit inside a resizable window. Currently, the image is viewed in a way that I want it to but only by providing some manually adjusted values to the initial view geometry. This doe not look neat. I also tried to refer to the solutions posted here: Graphics View and Pixmap Size
My current Window looks like this:
class ImageCheck(Ui_ImageCheck.Ui_MainWindow, QMainWindow):
def __init__(self, parent=None):
super(ImageCheck, self).__init__()
self.setupUi(self)
self.setWindowTitle("Image Analyzer")
self.crop_ratio_w = 1
self.crop_ratio_h = 1
self.path = None
self.scene = QGraphicsScene()
self.scene.clear()
self.image_item = QGraphicsPixmapItem()
# This is the approximate shift in coordinates of my initial view from the window
self.view.setGeometry(self.geometry().x()+ 10, self.geometry().y()+ 39,
self.geometry().width()- 55, self.geometry().height()- 110)
self.view.setAlignment(Qt.AlignCenter)
self.view.setFrameShape(QFrame.NoFrame)
def setImage(self, path):
self.path = path
self.crop_ratio_w = self.pixmap.width() / self.view.width()
self.crop_ratio_h = self.pixmap.height() / self.view.height()
pixmap = QPixmap(path)
smaller_pixmap = pixmap.scaled(self.view.width(), self.view.height(),
Qt.IgnoreAspectRatio, t.FastTransformation)
self.image_item.setPixmap(smaller_pixmap)
self.scene.addItem(self.image_item)
self.scene.setSceneRect(0, 0, self.view.width(), self.view.height())
self.view.setGeometry(0, 0, self.view.width(), self.view.height())
self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.view.setScene(self.scene)
self.view.setSceneSize()
def resizeEvent(self, event):
self.view.setGeometry(self.geometry().x()+ 10, self.geometry().y()+ 39,
self.geometry().width()- 55, self.geometry().height()- 110)
self.setImage(self.path)
My manual override was probably not a good idea when I tried to determine distances between two points. Even the scaled distance gives me a slightly wrong value.
I can not use your code because there are many hidden things so I will propose the next solution that is to rescale the view based on the scene each time the window changes its size. I have also implemented a signal that transports the clicked information in the image based on the coordinates of the image.
from PyQt5 import QtCore, QtGui, QtWidgets
class ClickableGraphicsView(QtWidgets.QGraphicsView):
clicked = QtCore.pyqtSignal(QtCore.QPoint)
def __init__(self, parent=None):
super(ClickableGraphicsView, self).__init__(parent)
scene = QtWidgets.QGraphicsScene(self)
self.setScene(scene)
self.pixmap_item = None
def setImage(self, path):
pixmap = QtGui.QPixmap(path)
self.pixmap_item = self.scene().addPixmap(pixmap)
self.pixmap_item.setShapeMode(
QtWidgets.QGraphicsPixmapItem.BoundingRectShape
)
def mousePressEvent(self, event):
if self.pixmap_item is not None:
if self.pixmap_item == self.itemAt(event.pos()):
sp = self.mapToScene(event.pos())
lp = self.pixmap_item.mapToItem(self.pixmap_item, sp)
p = lp.toPoint()
if self.pixmap_item.pixmap().rect().contains(p):
self.clicked.emit(p)
super(ClickableGraphicsView, self).mousePressEvent(event)
def resizeEvent(self, event):
self.fitInView(self.sceneRect(), QtCore.Qt.IgnoreAspectRatio)
super(ClickableGraphicsView, self).resizeEvent(event)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("Image Analyzer")
view = ClickableGraphicsView()
view.clicked.connect(print)
view.setImage("image.jpg")
label = QtWidgets.QLabel("Distance")
display = QtWidgets.QLCDNumber()
buttonbox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
)
widget = QtWidgets.QWidget()
self.setCentralWidget(widget)
lay = QtWidgets.QGridLayout(widget)
lay.addWidget(view, 0, 0, 1, 2)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(label)
hlay.addWidget(display)
hlay.addStretch()
lay.addLayout(hlay, 1, 0)
lay.addWidget(buttonbox, 1, 1)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I'm new to PyQt and I'm trying to create a system which dynamically adds widgets when the user presses add.
I want the same self.comboBox widget to get added above the Add button. I will also make a remove button but I believe that will be no problem.
Moreover, I would like certain checkboxes to appear next to the self.combobox when the user chooses an option (aka option is not -Select-).
Finally, how can I store the user's choices in the checkboxes and the combobox? Do I declare a variable or what exactly?
My code was too much to read, so this instead:
class myWindow(QWidget):
def __init__(self):
super().__init__()
self.init()
self.organize()
def init(self):
self.label = QLabel("Label")
self.comboBox = QComboBox(self)
self.comboBox.addItem("-Select-")
self.comboBox.addItem("1")
self.comboBox.addItem("2")
self.comboBox.addItem("3")
self.addbtn = QPushButton("Add")
self.addbtn.clicked.connect(self.addComboBox)
def organize(self):
grid = QGridLayout(self)
self.setLayout(grid)
grid.addWidget(Label, 0, 0, 0, 2)
grid.addWidget(self.comboBox, 1, 2, 1, 3)
grid.addWidget(self.addbtn, 2, 2)
def addComboBox(self):
#Code to add a combo box just like self.comboBox above addbtn and below all existing comboBoxes.
What I want
Sorry. If I understand you correctly, your example might look something like this:
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class CheckableComboBox(QComboBox):
def __init__(self, parent = None):
super(CheckableComboBox, self).__init__(parent)
self.parent = parent
self.setView(QListView(self))
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QStandardItemModel(self))
def handleItemPressed(self, index):
item = self.model().itemFromIndex(index)
if item.checkState() == Qt.Checked:
item.setCheckState(Qt.Unchecked)
else:
item.setCheckState(Qt.Checked)
self.on_selectedItems()
def checkedItems(self):
checkedItems = []
for index in range(self.count()):
item = self.model().item(index)
if item.checkState() == Qt.Checked:
checkedItems.append(item)
return checkedItems
def on_selectedItems(self):
selectedItems = self.checkedItems()
self.parent.lblSelectItem.setText("")
for item in selectedItems:
self.parent.lblSelectItem.setText("{} {} "
"".format(self.parent.lblSelectItem.text(), item.text()))
class ExampleWidget(QGroupBox):
def __init__(self, numAddWidget):
QGroupBox.__init__(self)
self.numAddWidget = numAddWidget
self.numAddItem = 1
self.setTitle("Title {}".format(self.numAddWidget))
self.initSubject()
self.organize()
def initSubject(self):
self.lblName = QLabel("Label Title {}".format(self.numAddWidget), self)
self.lblSelectItem = QLabel(self)
self.teachersselect = CheckableComboBox(self)
self.teachersselect.addItem("-Select {}-".format(self.numAddItem))
item = self.teachersselect.model().item(0, 0)
item.setCheckState(Qt.Unchecked)
self.addbtn = QPushButton("ComboBoxAddItem...", self)
self.addbtn.clicked.connect(self.addTeacher)
def organize(self):
grid = QGridLayout(self)
self.setLayout(grid)
grid.addWidget(self.lblName, 0, 0, 1, 3)
grid.addWidget(self.lblSelectItem, 1, 0, 1, 2)
grid.addWidget(self.teachersselect, 1, 2)
grid.addWidget(self.addbtn, 3, 2)
def addTeacher(self):
self.numAddItem += 1
self.teachersselect.addItem("-Select {}-".format(self.numAddItem))
item = self.teachersselect.model().item(self.numAddItem-1, 0)
item.setCheckState(Qt.Unchecked)
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.numAddWidget = 1
self.initUi()
def initUi(self):
self.layoutV = QVBoxLayout(self)
self.area = QScrollArea(self)
self.area.setWidgetResizable(True)
self.scrollAreaWidgetContents = QWidget()
self.scrollAreaWidgetContents.setGeometry(0, 0, 200, 100)
self.layoutH = QHBoxLayout(self.scrollAreaWidgetContents)
self.gridLayout = QGridLayout()
self.layoutH.addLayout(self.gridLayout)
self.area.setWidget(self.scrollAreaWidgetContents)
self.add_button = QPushButton("Add Widget")
self.layoutV.addWidget(self.area)
self.layoutV.addWidget(self.add_button)
self.add_button.clicked.connect(self.addWidget)
self.widget = ExampleWidget(self.numAddWidget)
self.gridLayout.addWidget(self.widget)
self.setGeometry(700, 200, 350, 300)
def addWidget(self):
self.numAddWidget += 1
self.widget = ExampleWidget(self.numAddWidget)
self.gridLayout.addWidget(self.widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyApp()
w.show()
sys.exit(app.exec_())