In my application, I have an image and I'm trying to create a button under the application. Instead, the button appears on top of the image.
This is my code so far:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QPushButton
from PyQt5.QtGui import QPixmap
class Example(QWidget):
def __init__(self):
super().__init__()
self.grid = QGridLayout()
self.im = QPixmap("image1.png")
self.label = QLabel()
self.label.setPixmap(self.im)
self.grid.addWidget(self.label, 1, 1)
self.setLayout(self.grid)
self.new = QPushButton("Restart", self)
self.grid.addWidget(self.label, 1, 2)
self.setLayout(self.grid)
self.setWindowTitle("My Application")
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
I suspect it has something to do with pixmap not being recognized as an actual object, so the button just disregards its placement. But I'm not sure, anyone know why its not working? Thanks for your help!
The image is what the GUI currently looks like
CodePudding user response:
It looks like you're adding the self.label widget twice to the grid layout, but you're not adding the button to the layout at all. You need to add the button to the grid layout using the addWidget() method, just like you're doing for the self.label widget.
Here's an example of how you could modify your code to add the button to the layout and place it underneath the image:
class Example(QWidget):
def __init__(self):
super().__init__()
self.grid = QGridLayout()
self.im = QPixmap("image1.png")
self.label = QLabel()
self.label.setPixmap(self.im)
# Add the label widget to the grid layout
self.grid.addWidget(self.label, 0, 0)
# Create the button and add it to the grid layout
self.new = QPushButton("Restart", self)
self.grid.addWidget(self.new, 1, 0)
self.setLayout(self.grid)
self.setWindowTitle("My Application")
self.show()
In this example, I've added the button to the grid layout on the second row, first column (indexes 1, 0), so it will appear underneath the image.
I hope this helps! Let me know if you have any other questions.