Reputation:
I am trying to create a Pyqt5 file to open another window with the click of Push for Window button and also to open an image when Process button is clicked.
While running the program I am getting these lines as errors.
Traceback (most recent call last):
File "untitled.py", line 52, in <module>
w = MainWindow()
File "untitled.py", line 27, in __init__
layout.addWidget(self.button)
NameError: name 'layout' is not defined
The Program For the same is attached below.
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget
import sys
class AnotherWindow(QWidget):
def __init__(self):
super().__init__()
global layout
layout = QVBoxLayout()
self.label = QLabel("Another Window")
layout.addWidget(self.label)
self.setLayout(layout)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.button = QPushButton("Push for Window")
self.button.clicked.connect(self.show_new_window)
layout.addWidget(self.button)
self.btn1 = QPushButton("Process")
self.btn1.clicked.connect(self.show_new_window)
layout.addWidget(self.btn1)
def getImage(self):
fname = QFileDialog.getOpenFileName(self, 'Open file','/home/ucal/Desktop/', "Image files (*.jpg )")
global imagePath
imagePath = fname[0]
global pixmap
pixmap = QPixmap(imagePath)
print(imagePath)
self.label.setPixmap(QPixmap(pixmap))
self.resize(pixmap.width(), pixmap.height())
def show_new_window(self, checked):
self.w = AnotherWindow()
self.w.show()
app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()
Upvotes: 0
Views: 632
Reputation: 244262
You have the following errors:
Using "global X" does not create a global variable, it only indicates that variable X is already a global variable and wants to be reused. In general it is a bad practice and in your case it does not provide any advantage and on the contrary causes confusion.
In the MainWindow constructor you have not created the "layout" object so you get that error.
Considering the above, the solution is:
class AnotherWindow(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout(self)
self.label = QLabel("Another Window")
layout.addWidget(self.label)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QVBoxLayout(central_widget)
self.button = QPushButton("Push for Window")
self.button.clicked.connect(self.show_new_window)
layout.addWidget(self.button)
self.btn1 = QPushButton("Process")
self.btn1.clicked.connect(self.show_new_window)
layout.addWidget(self.btn1)
def getImage(self):
fname = QFileDialog.getOpenFileName(
self, "Open file", "/home/ucal/Desktop/", "Image files (*.jpg )"
)
imagePath = fname[0]
pixmap = QPixmap(imagePath)
print(imagePath)
self.label.setPixmap(QPixmap(pixmap))
self.resize(pixmap.width(), pixmap.height())
def show_new_window(self, checked):
self.w = AnotherWindow()
self.w.show()
Upvotes: 1