I have this code:
class Window(QWidget):
def __init__(self):
super().__init__()
def init_gui(self):
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.new1()
self.new2()
self.showMaximized()
def create_scroll_area(self):
scroll_area = QScrollArea()
widget = QWidget()
scroll_area.setWidget(widget)
layout = QVBoxLayout()
widget.setLayout(layout)
button = QPushButton("Ahoj")
layout.addWidget(button)
self.layout.addLayout(layout)
def new1(self):
self.create_scroll_area()
def new2(self):
self.create_scroll_area()
I get this error message:
QLayout::addChildLayout: layout "" already has a parent
What's wrong?
Who is layout's parent? Widget? I also tried self.widget instead of widget and it still does not work.
Please try this code.
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QWidget):
def __init__(self, parent=None):
super().__init__(parent=None)
self.init_gui()
def init_gui(self):
self.create_scroll_area()
self.showMaximized()
def create_scroll_area(self):
scroll_area = QScrollArea()
widget = QWidget()
layout = QVBoxLayout()
button = QPushButton("Ahoj")
layout.addWidget(button)
widget.setLayout(layout)
scroll_area.setWidget(widget)
self.setLayout(layout)
def main():
app = QApplication([])
window = Window()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Let's revise from A to Z.
1 to write self.init_gui() in __init__ constructor.
If you don't do it, you can't execute init_gui method at the first time.
2.setLayout() or setWidget() should be written at the last place at least.
In python, we prepare the things we want to show, and set them on the mainwidget, and show them at the last time.
3.please pay attention to self.layout name.
Widget has originally setLayout() method. and layout() method.
If you make self.layout = ***, you crush the original method of QWidget.
4. it may as well delete new1 and new2 method.
please call them directly.
5. please look create_scroll_area method.
You make three widget.QScrollArea,QWidget,QPushButton.
and make a layout object.and you set the layout into QWidget.
But you set the QWidget before the widget set the layout.
It is not good order for coding.
You make QPushButton but the button doesn't belong to any widget.
Because you set the button on the self.layout certainly, but if you want to show it, you must setLayout(self.layout) at the last position.
Related
I am trying to stop a widget from expanding by setting its size policy but things are not working.
The following code runs:
from PyQt5.QtWidgets import*
import pyqtgraph as pg
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.layout = QHBoxLayout()
self.left_widget = pg.GraphicsLayoutWidget()
self.layout.addWidget(self.left_widget)
self.right_widget = RightWidget()
#self.right_widget.groupbox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.layout.addWidget(self.right_widget)
self.widget = QWidget()
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
class RightWidget(QWidget):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
self.groupbox = QGroupBox()
self.groupbox.setTitle("some title")
#self.groupbox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.groupboxlayout = QVBoxLayout()
self.button1 = QPushButton ("1")
self.groupboxlayout.addWidget(self.button1)
self.button2 = QPushButton ("2")
self.groupboxlayout.addWidget(self.button2)
self.button3 = QPushButton ("3")
self.groupboxlayout.addWidget(self.button3)
self.groupbox.setLayout(self.groupboxlayout)
self.layout.addWidget(self.groupbox)
self.button4 = QPushButton ("4")
self.layout.addWidget(self.button4)
self.button5 = QPushButton ("5")
self.layout.addWidget(self.button5)
self.setLayout(self.layout)
if __name__ == '__main__':
import sys
system_app = QApplication(sys.argv)
main = MainWindow()
main.show()
system_app.exec()
It gives:
The specific choice of widgets should not matter. The point is that, there is a large widget on the left and there are smaller widgets on the right that is not large enough to fill the column. I want to modify the above code to shrink the widgets on the right hand side. That is:
In words, I want the widgets to shrink to top and bottom of the page in a way taking minimum space (and hence leaving the middle empty).
I attempted to use QSizePolicy to achieve the desired result. The commented lines seem to have no impact on the page at all. I don't know what went wrong.
This question already has answers here:
PyQT Navigation between layouts
(2 answers)
Closed 1 year ago.
How to get back my MainWindow ?
From my MainWindow. If I Press either the "Open Left Box" button or "Open Right Box" button, it's worked and at the same time, If I press the "Back" Button from Left Box, nothing will happen. How to obtain the main window? (Simply, I want to know how to set Layouts and remove layouts in setcentral Widgets)
import sys,os
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Class_MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Main Window")
self.initUI()
def initUI(self):
self.widgets()
self.layouts()
def widgets(self):
self.Masterbtn = QPushButton("Master")
self.transbtn = QPushButton("tanscation")
self.reportbtn = QPushButton("Reports")
self.masterlbl = QLabel("Master Label")
self.translbl = QLabel("transcation label")
self.reportlbl = QLabel("Report Label")
self.leftboxbtn = QPushButton("Open Left Box")
self.leftboxbtn.clicked.connect(self.leftboxopn)
self.rightboxbtn = QPushButton("Open Right Box")
self.rightboxbtn.clicked.connect(self.rightboxopn)
self.backbtn =QPushButton("Back")
self.backbtn.clicked.connect(self.mainwindow)
def layouts(self):
self.mainbox = QVBoxLayout()
self.mainbox.addWidget(self.leftboxbtn)
self.mainbox.addWidget(self.rightboxbtn)
self.leftbox = QVBoxLayout()
self.leftbox.addWidget(self.Masterbtn)
self.leftbox.addWidget(self.transbtn)
self.leftbox.addWidget(self.reportbtn)
self.leftbox.addWidget(self.backbtn)
self.rightbox = QVBoxLayout()
self.rightbox.addWidget(self.masterlbl)
self.rightbox.addWidget(self.translbl)
self.rightbox.addWidget(self.reportlbl)
# self.rightbox.addWidget(self.backbtn)
widget = QWidget()
widget.setLayout(self.mainbox)
self.setCentralWidget(widget)
def leftboxopn(self):
self.setWindowTitle("Left Box ")
widget = QWidget()
widget.setLayout(self.leftbox)
self.setCentralWidget(widget)
def rightboxopn(self):
self.setWindowTitle("Right Box")
widget = QWidget()
widget.setLayout(self.rightbox)
self.setCentralWidget(widget)
def mainwindow(self):
self.setWindowTitle("Main Window")
widget = QWidget()
widget.setLayout(self.mainbox)
self.setCentralWidget(widget)
def main():
app = QApplication(sys.argv)
mainwindow = Class_MainWindow()
mainwindow.show()
sys.exit(app.exec_())
if __name__ =="__main__":
main()
You cannot "get back" anything, because everytime you use setCentralWidget() the existing widget gets deleted, as the documentation explains:
Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time.
When you call setCentralWidget() on another widget, the previous is completely deleted, including all its children. When a Qt object is deleted, all its child objects gets deleted along with it, and the result is that the self.mainbox you created in the beginning doesn't exist any more (the python object exists, but remember that PyQt objects are only a reference to the actual Qt objects: a Qt object can be deleted if Qt requires it, even if the python reference still exists).
In substance (and, in any case), you should not replace the central widget everytime, but use a paged widget like QStackedWidget as the central widget instead, and then switch to the other interfaces using its functions: setCurrentIndex() or setCurrentWidget().
In order to properly use it, all child widgets must be added to a QWidget container, which will then be added as individual "pages" to QStackedWidget:
class Class_MainWindow(QMainWindow):
# ...
def layouts(self):
self.mainContainer = QWidget()
self.mainbox = QVBoxLayout(self.mainContainer)
self.mainbox.addWidget(self.leftboxbtn)
self.mainbox.addWidget(self.rightboxbtn)
self.leftContainer = QWidget()
self.leftbox = QVBoxLayout(self.leftContainer)
self.leftbox.addWidget(self.Masterbtn)
self.leftbox.addWidget(self.transbtn)
self.leftbox.addWidget(self.reportbtn)
self.leftbox.addWidget(self.backbtn)
self.rightContainer = QWidget()
self.rightbox = QVBoxLayout(self.rightContainer)
self.rightbox.addWidget(self.masterlbl)
self.rightbox.addWidget(self.translbl)
self.rightbox.addWidget(self.reportlbl)
# self.rightbox.addWidget(self.backbtn)
self.stackedWidget = QStackedWidget()
self.setCentralWidget(self.stackedWidget)
self.stackedWidget.addWidget(self.mainContainer)
self.stackedWidget.addWidget(self.leftContainer)
self.stackedWidget.addWidget(self.rightContainer)
def leftboxopn(self):
self.setWindowTitle("Left Box ")
self.stackedWidget.setCurrentWidget(self.leftContainer)
def rightboxopn(self):
self.setWindowTitle("Right Box")
self.stackedWidget.setCurrentWidget(self.rightContainer)
def mainwindow(self):
self.setWindowTitle("Main Window")
self.stackedWidget.setCurrentWidget(self.mainContainer)
I am implement my-self label, but some widget is disappear.
My code is:
from PyQt5.QtWidgets import *
import sys
class TypeManagerLabel(QLabel):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
btnLayout = QHBoxLayout()
self.__nameLineEdit = QLineEdit()
self.__opBtn = QPushButton('Add/Remove')
self.__colorBtn = QPushButton('Color')
btnLayout.addWidget(self.__nameLineEdit)
btnLayout.addWidget(self.__opBtn)
layout.addLayout(btnLayout)
class MyWin(QLabel):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
lab1 = TypeManagerLabel()
layout.addWidget(lab1)
# layout.addStretch()
lab2 = QPushButton('test')
layout.addWidget(lab2)
app = QApplication(sys.argv)
dialog = MyWin()
dialog.show()
app.exec_()
Currently, the label is OK, and the result should be:
Now, I want the QLineEdit should be located on the top of the label, thus I add a stretch. And the code is:
class MyWin(QLabel):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
lab1 = TypeManagerLabel()
layout.addWidget(lab1)
layout.addStretch() ###################### add the stretch
lab2 = QPushButton('test')
layout.addWidget(lab2)
And the result is:
In the above figure, the QLineEdit is disappeared.
#
My environment is:
win 10
python 3.7.8
pyqt5 5.14.0
--------------------------------update ----------------------------------
Thank for the suggestion from musicamante and Heike, subclass QWidget instead of QLabel. But the new bug is reported after I add some new widget. The code is:
from PyQt5.QtWidgets import *
import sys
class TypeManagerLabel(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
btnLayout = QHBoxLayout()
self.__nameLineEdit = QLineEdit()
self.__opBtn = QPushButton('Add')
btnLayout.addWidget(self.__nameLineEdit)
btnLayout.addWidget(self.__opBtn)
layout.addLayout(btnLayout)
infoLabel = QLabel()
layout.addWidget(infoLabel)
self.__infoLayout = QVBoxLayout()
infoLabel.setLayout(self.__infoLayout)
self.__opBtn.clicked.connect(self.addRemoveSlot)
def addRemoveSlot(self, checked=False):
name = self.__nameLineEdit.text()
layout = QHBoxLayout()
checkBox = QCheckBox()
lineEdit = QLineEdit(name)
layout.addWidget(checkBox)
layout.addWidget(lineEdit)
self.__infoLayout.addLayout(layout)
class MyWin(QLabel):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
lab1 = TypeManagerLabel()
layout.addWidget(lab1)
# layout.addStretch()
lab2 = QPushButton('test')
layout.addWidget(lab2)
app = QApplication(sys.argv)
dialog = MyWin()
dialog.show()
app.exec_()
When I input a string in the QLineEdit, and click the "Add" button, the result is:
The above figure is what I expected.
But if I add stretch with the code:
class MyWin(QLabel):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
lab1 = TypeManagerLabel()
layout.addWidget(lab1)
layout.addStretch() ###################### add the stretch
lab2 = QPushButton('test')
layout.addWidget(lab2)
Then, if I input a string in the QLineEdit and click the 'Add' button, the expected widget would not appear.
QLabel is a very special type of widget. While it seems very simple, it is not: it has its own behavior when dealing with sizes, and that's in order to accomodate all requirements a widget that is primarily based on (possibly) variable text size, not only horizontally, but vertically also.
That said, one should never try to add layouts and child widgets to classes that are not intended to be used as container, most importantly it should not be done on widgets with peculiar behavior like QLabel.
Using such a widget to contain other widgets is not only a very bad idea, but also completely useless, as you're not actually using the real features a QLabel provides (showing text or images).
To add children and layouts, just use a nested layout, a plain QWidget class, or any other container widgets like QGroupBox or QFrame.
Even after the comments, you're still trying to add widgets to a QLabel. Remove that label, and just add the layout to the main one.
class TypeManagerLabel(QWidget):
def __init__(self):
super().__init__()
# ...
layout.addLayout(btnLayout)
self.__infoLayout = QVBoxLayout()
layout.addLayout(self.__infoLayout)
self.__opBtn.clicked.connect(self.addRemoveSlot)
# ...
I am making a GUI with PyQt, and I am having issues with my MainWindow class. The window doesn't show widgets that I define in other classes, or it will show a small portion of the widgets in the top left corner, then cut off the rest of the widget.
Can someone please help me with this issue?
Here is some example code showing my issue.
import sys
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
self.resize(300, 400)
self.centralWidget = QtGui.QWidget(self)
self.hbox = QtGui.QHBoxLayout(self.centralWidget)
self.setLayout(self.hbox)
names = ['button1', 'button2', 'button3']
testButtons = buttonFactory(names, parent=self)
self.hbox.addWidget(testButtons)
class buttonFactory(QtGui.QWidget):
def __init__(self, names, parent=None):
super(buttonFactory, self).__init__(parent=parent)
self.vbox = QtGui.QVBoxLayout()
self.setLayout(self.vbox)
for name in names:
btn = QtGui.QPushButton(name)
self.vbox.addWidget(btn)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = MainWindow()
gui.show()
app.exec_()
A QMainWindow has a central widget that is a container in which you should add your widgets. It has its own layout. The layout of the QMainWindow is for toolbars and such. The centralWidget must be set with the setCentralWidget method. It isn't enough to just call it self.centralWidget
Use the following three lines instead.
self.setCentralWidget(QtGui.QWidget(self))
self.hbox = QtGui.QHBoxLayout()
self.centralWidget().setLayout(self.hbox)
I am trying to show set of actions when a button is clicked and other set of options if another button is clicked.
Below is the code:
class Screen(QWidget):
def __init__(self):
super(Screen, self).__init__()
layout = QHBoxLayout(self)
self.all_running()
layout.addWidget(self.running_full_widget)
self.actions('1')
layout.addWidget(self.actions_full_widget)
self.setLayout(layout)
self.show()
def all_running(self):
self.running_full_widget = QWidget()
runnning_full_layout= QVBoxLayout()
button1 = QPushButton("btn1")
button2 = QPushButton("btn2")
button1.clicked.connect(lambda: self.actions('2'))
button2.clicked.connect(lambda: self.actions('3'))
runnning_full_layout.addWidget(button1)
runnning_full_layout.addWidget(button2)
self.running_full_widget.setLayout(runnning_full_layout)
def actions(self,value):
self.actions_full_widget= QWidget()
val = int(value)
print(val)
actions_layout = QVBoxLayout()
for i in range(val):
actions_item = QLabel(str(i))
actions_layout.addWidget(actions_item)
self.actions_full_widget.setLayout(actions_layout)
app = QApplication(sys.argv)
Gui = Screen()
sys.exit(app.exec_())
When button is clicked i can see the value is updated but it is not updated in the main layout.
how can i dynamically update the widgets ?
How can I do that in cases where i need to add widgets based on a dynamic value.
did i miss anything with signals and slots?
Kindly correct me if i am wrong. Thanks
Your code was almost there. The problem you are seeing is the widgets were being added but never removed. The following code could be simplified, but I tried to keep it close to yours so you could see the changes more easily.
The main change is now there is a class member screen_layout and the widgets are added/removed from it inside actions().
import sys
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget, QPushButton, QLabel, QApplication
class Screen(QWidget):
def __init__(self):
super(Screen, self).__init__()
layout = QHBoxLayout(self)
self.screen_layout = layout
self.all_running()
layout.addWidget(self.running_full_widget)
self.actions_full_widget = None
self.actions('1')
# layout.addWidget(self.actions_full_widget)
self.setLayout(layout)
self.show()
def all_running(self):
self.running_full_widget = QWidget()
runnning_full_layout= QVBoxLayout()
button1 = QPushButton("btn1")
button2 = QPushButton("btn2")
button1.clicked.connect(lambda: self.actions('2'))
button2.clicked.connect(lambda: self.actions('3'))
runnning_full_layout.addWidget(button1)
runnning_full_layout.addWidget(button2)
self.running_full_widget.setLayout(runnning_full_layout)
def actions(self,value):
# Remove any previously added widget
if self.actions_full_widget is not None:
self.screen_layout.removeWidget(self.actions_full_widget)
self.actions_full_widget.deleteLater()
self.actions_full_widget= QWidget()
val = int(value)
print(val)
actions_layout = QVBoxLayout()
for i in range(val):
actions_item = QLabel(str(i))
actions_layout.addWidget(actions_item)
self.actions_full_widget.setLayout(actions_layout)
self.screen_layout.addWidget(self.actions_full_widget)
app = QApplication(sys.argv)
Gui = Screen()
sys.exit(app.exec_())