I want to get a string from the main window to use in a window triggered with a click. I know how to do it by putting all statements into a single class, but now I'm trying to do the same thing with one class per window. Here is the code:
import sys
from PyQt4 import QtGui
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super().__init__()
self.initUI()
def initUI(self):
self.value = QtGui.QLineEdit('23')
self.button = QtGui.QPushButton('Open Dialog')
self.button.clicked.connect(self.openDialog)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.value)
vbox.addWidget(self.button)
self.setLayout(vbox)
def openDialog(self):
self.entry = self.value.text()
print(self.entry)
Dialog().exec_()
class Dialog(QtGui.QDialog):
def __init__(self, parent=Window):
super().__init__()
win = Window()
self.text = win.entry
self.label = QtGui.QLabel(self.text)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(self.label)
self.setLayout(hbox)
def main():
app = QtGui.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
But I'm getting the error "AttributeError: 'Window' object has no attribute 'entry'" and I don't know any other way to try fix it. Can someone help me with it?
Create an instance of Dialog in the openDialog method, so that you can access its attributes directly. That way, the two classes can operate more independently, and you won't need to access the Window class from within the Dialog class:
def openDialog(self):
dialog = Dialog(self)
dialog.label.setText(self.value.text())
dialog.exec_()
print(dialog.label.text())
class Dialog(QtGui.QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.label = QtGui.QLabel(self)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(self.label)
self.setLayout(hbox)
Here
win = Window()
self.text = win.entry
you declare a new window and accesing its entry field but on your window class
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super().__init__()
self.initUI()
the entry field is not constructed.
So
Either you want to create a new window, so you have to put the self.entry on the constructor
You want to use the existing window an access its entry after calling openDialog
Edit:
Maybe here
class Dialog(QtGui.QDialog):
def __init__(self, parent=Window):
super().__init__()
you are initializing the class wrong. The parent constructor should be called with parent=Window too. Then from inside the dialog you could reference the window by doing self.parent
Related
I've been trying to make this work, but it just doesn't. I get no errors, just plain noncompliance. It just does not want to add the QListWidget items, or change the QLabel.
I made a MainWindowClass. It it's main widget I have a layout and a button. In it's dockwidget I have a QListWidget.
I made a signal from the button and connected it to a slot in the dockwidget's list.
The connection is there. When I press the button, the method in the dockwidgetcontents class is running.
But it does not add the items to the listwidget. And does not produce any errors.
Here is the code:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class AppClass:
def __init__(self):
super().__init__()
app = QApplication(sys.argv)
window = MainWindowClass()
window.show()
sys.exit(app.exec_())
class MainWindowClass(QMainWindow):
def __init__(self):
super().__init__()
self.init_UI()
self.TheDockWidget()
def init_UI(self):
self.setGeometry(100, 100, 400, 200)
self.setWindowTitle("Test App")
self.setCentralWidget(MainWidgetClass())
def TheDockWidget(self):
self.dockWidget = QDockWidget('Status:')
self.dockWidget.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable)
self.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget)
self.dockWidget.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
self.dockWidget.setWidget(DockWidgetContents())
class DockWidgetContents(QWidget):
def __init__(self):
super().__init__()
self.init_UI()
def init_UI(self):
layout = QVBoxLayout()
self.setLayout(layout)
self.button3 = QPushButton()
self.button3.setText("button3")
layout.addWidget(self.button3)
self.listwidget = QListWidget()
layout.addWidget(self.listwidget)
self.listwidget.addItem("Ready.")
self.label = QLabel("initial")
layout.addWidget(self.label)
#pyqtSlot(str, str, int)
def _add_item(self, strA, strB, int1):
self.label.setText("yes") # why does this not work??
self.listwidget.addItem(strA) # why does this not work??
self.listwidget.addItem(strB) # why does this not work??
self.listwidget.addItem(str(int1)) # why does this not work??
print(strA, strB, int1) # but this works fine.
class MainWidgetClass(QWidget):
def __init__(self):
super().__init__()
self.init_UI()
def init_UI(self):
mainLayout = QGridLayout()
self.setLayout(mainLayout)
mainLayout.addWidget(TopLeftWidgetClass(), 0, 0)
class TopLeftWidgetClass(QWidget):
signal = pyqtSignal(str, str, int)
def __init__(self):
super().__init__()
self.init_UI()
def init_UI(self):
layout = QHBoxLayout()
self.setLayout(layout)
self.button1 = QPushButton("button1")
layout.addWidget(self.button1)
self.button1.clicked.connect(self.start)
def start(self):
otherClass = DockWidgetContents()
self.signal.connect(otherClass._add_item)
self.signal.emit("one", "two", 3)
if __name__ == '__main__':
AppClass()
I also read all the suggested questions when I typed my question into the form, but I must be not understanding something vital or prerequisite to this.
While I find all your answers to other questions extremely valuable, I'd appreciate if the answer would point me to the reference that I'm missing, so I can understand the problem, rather than just copy/paste the fixed code.
The main problem is that you're trying to connect to a new instance of DockWidgetContents, which gets also immediately deleted as soon as start() returns.
That new instance is obviously useless, as one already exists, but you have no direct ways to get it, because you create all classes "on the fly" when you add widgets to layouts and parents.
Remember that, while creating "instances on the fly" is not technically a problem, it doesn't allow you to keep references to those instances.
You have to create appropriate references to widgets and correctly connect them.
Here you can see the modifications required:
class MainWindowClass(QMainWindow):
def __init__(self):
super().__init__()
self.init_UI()
self.TheDockWidget()
self.mainWidget.topLeftWidget.signal.connect(
self.dockWidgetContents._add_item)
def init_UI(self):
self.setGeometry(100, 100, 400, 200)
self.setWindowTitle("Test App")
self.mainWidget = MainWidgetClass()
self.setCentralWidget(self.mainWidget)
def TheDockWidget(self):
self.dockWidget = QDockWidget('Status:')
self.dockWidget.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable)
self.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget)
self.dockWidget.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
self.dockWidgetContents = DockWidgetContents()
self.dockWidget.setWidget(self.dockWidgetContents)
class MainWidgetClass(QWidget):
def __init__(self):
super().__init__()
self.init_UI()
def init_UI(self):
mainLayout = QGridLayout()
self.setLayout(mainLayout)
self.topLeftWidget = TopLeftWidgetClass()
mainLayout.addWidget(self.topLeftWidget, 0, 0)
I have build a small application using PyQt and as far as I know QStackedWidget is used for making multipage applications. The issue is that it is opening multiple pages and also I'm unable to redirect to class Xyz using button in class Abc.
main.py
from PyQt4 import QtGui, QtCore
import sys
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.stacked_widget = QtGui.QStackedWidget()
layout = QtGui.QVBoxLayout()
layout.setContentsMargins(0,0,0,0)
layout.addWidget(self.stacked_widget)
widget = QtGui.QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
widget_1 = Abc(self.stacked_widget)
widget_2 = Xyz(self.stacked_widget)
self.stacked_widget.addWidget(widget_1)
self.stacked_widget.addWidget(widget_2)
self.showMaximized()
class Abc(QtGui.QWidget):
def __init__(self, stacked_widget, parent=None):
super(Abc, self).__init__(parent)
self.stacked_widget = stacked_widget
self.frame = QtGui.QFrame()
self.frame_layout = QtGui.QVBoxLayout()
self.button = QtGui.QPushButton('Click me!')
self.button.clicked.connect(self.click)
self.frame_layout.addWidget(self.button)
self.frame.setLayout(self.frame_layout)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.frame)
self.setLayout(self.layout)
self.showMaximized()
def click(self):
print("You clicked me!")
self.stacked_widget.setCurrentIndex(1)
class Xyz(QtGui.QWidget):
def __init__(self, parent=None):
super(Xyz, self).__init__(parent)
self.frame_layout = QtGui.QStackedLayout()
self.page1 = Page("Page 1", self.frame_layout)
self.page2 = Page("Page 2", self.frame_layout)
self.frame_layout.addWidget(self.page1)
self.frame_layout.addWidget(self.page2)
class Page(QtGui.QWidget):
def __init__(self, text, frame_layout, parent=None):
super(Page, self).__init__(parent)
print(self.width(), self.height())
self.frame_layout = frame_layout
self.frame = QtGui.QFrame()
self.frame_layout = QtGui.QVBoxLayout()
self.frame.setStyleSheet("background-color: rgb(191, 191, 191)")
self.label = QtGui.QLabel()
self.label.setText(text)
self.frame_layout.addWidget(self.label, alignment=QtCore.Qt.AlignCenter)
self.frame.setLayout(self.frame_layout)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.frame)
self.layout.setContentsMargins(0,0,0,0)
self.setLayout(self.layout)
self.showMaximized()
print(self.width(), self.height())
if __name__ == "__main__":
app = QtGui.QApplication([])
window = Window()
window.show()
sys.exit(app.exec_())
The main problem is that you are not setting the QStackedLayout for the Xyz widget, the result is that all pages will actually appear as top level windows.
When a widget is added to a layout, it takes ownership of it; if the layout is already set to a widget, then the widget that was added to the layout becomes reparented to the other. The same happens if you set the layout afterwards.
Why does it show the first page as a separate window? And why doesn't it show the second?
When a new widget is created without a parent, it becomes a top level window; when a widget is added to a new stacked layout, Qt automatically tries to show it; you didn't set the layout to anything (which would reparent it as explained before), and the result is that the first page is shown as a standalone window.
Now, since the first "screen" is going to be shown only the first time, you can set that widget as the central widget, and then set a Xyz instance (which is actually a QStackedWidget subclass) as a new central widget.
Note that you don't need to use QWidget to add a QFrame if that's the only parent widget shown: you can just subclass QFrame.
This is a much simpler and cleaner version of your code:
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.startPage = Abc()
self.setCentralWidget(self.startPage)
self.startPage.startRequest.connect(self.buildPages)
def buildPages(self):
self.pages = Xyz()
self.setCentralWidget(self.pages)
class Abc(QtGui.QFrame):
startRequest = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(Abc, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)
self.button = QtGui.QPushButton('Click me!')
self.button.clicked.connect(self.startRequest)
layout.addWidget(self.button)
class Xyz(QtGui.QStackedWidget):
def __init__(self, parent=None):
super(Xyz, self).__init__(parent)
self.page1 = Page("Page 1")
self.page2 = Page("Page 2")
self.addWidget(self.page1)
self.addWidget(self.page2)
self.page1.switchRequest.connect(lambda: self.setCurrentIndex(1))
self.page2.switchRequest.connect(lambda: self.setCurrentIndex(0))
class Page(QtGui.QFrame):
switchRequest = QtCore.pyqtSignal()
def __init__(self, text, parent=None):
super(Page, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)
# set the background only for QFrame subclasses (which also includes
# QLabel), this prevents setting the background for other classes,
# such as the push button
self.setStyleSheet('''
QFrame {
background-color: rgb(191, 191, 191)
}
''')
# when adding a widget to a layout, the layout tries to automatically
# make it as big as possible (based on the widget's sizeHint); so you
# should not use the alignment argument for layout.addWidget(), but for
# the label instead
self.label = QtGui.QLabel(text, alignment=QtCore.Qt.AlignCenter)
layout.addWidget(self.label)
self.switchButton = QtGui.QPushButton('Switch')
layout.addWidget(self.switchButton)
self.switchButton.clicked.connect(self.switchRequest)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
I have a main Window derived form QMainWindow that may show different Widgets, depending on the task at hand.
I created a simplified example below:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MainWindow(QMainWindow):
def __init__(self, parent=None):
'''
Constructor
'''
QMainWindow.__init__(self, parent)
self.central_widget = QStackedWidget()
self.setCentralWidget(self.central_widget)
self.start_screen = Start(self)
self.second_screen = Second(self)
self.central_widget.addWidget(self.start_screen)
self.central_widget.addWidget(self.second_screen)
self.central_widget.setCurrentWidget(self.start_screen)
class Start(QWidget):
def __init__(self, parent=None):
super(Start, self).__init__(parent)
layout = QHBoxLayout()
button = QPushButton(text=QString('Push me!'))
layout.addWidget(button)
self.setLayout(layout)
self.connect(button, SIGNAL("clicked()"), self.change_widget)
def change_widget(self):
self.parent().setCurrentWidget(
self.parent().parent().second_screen)
class Second(QWidget):
def __init__(self, parent=None):
super(Second, self).__init__(parent)
layout = QHBoxLayout()
button = QPushButton(text=QString('Back to Start!'))
layout.addWidget(button)
self.setLayout(layout)
self.connect(button, SIGNAL("clicked()"), self.change_widget)
def change_widget(self):
self.parent().setCurrentWidget(
self.parent().parent().start_screen)
app = QApplication(sys.argv)
myWindow = MainWindow(None)
myWindow.show()
app.exec_()
This toggles between two different central widgets, nevertheless I found the handling with parent() functions tedious, and I'd like to know if there is a better method to organise the widgets.
The setCurrentWidget method will probably be always accessible with one parent() statement, but if for any reasons the hierarchy-depth changes, is there a better method to access the QMainWindow than parent().parent()? Or would I just re-create the Widget every time a button is clicked (I assume, if this would be a widget with data-Input possibilities, these data would be lost, which is annoying).
I appreciate any suggestions for improvement.
You should be using Signals. This allows any parent hierarchy and the child widgets don't have to have any knowledge of how they're being used or what order they're being displayed in. The main widget handles it all.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class MainWindow(QMainWindow):
def __init__(self, parent=None):
'''
Constructor
'''
QMainWindow.__init__(self, parent)
self.central_widget = QStackedWidget()
self.setCentralWidget(self.central_widget)
self.start_screen = Start(self)
self.second_screen = Second(self)
self.central_widget.addWidget(self.start_screen)
self.central_widget.addWidget(self.second_screen)
self.central_widget.setCurrentWidget(self.start_screen)
self.start_screen.clicked.connect(lambda: self.central_widget.setCurrentWidget(self.second_screen))
self.second_screen.clicked.connect(lambda: self.central_widget.setCurrentWidget(self.start_screen))
class Start(QWidget):
clicked = pyqtSignal()
def __init__(self, parent=None):
super(Start, self).__init__(parent)
layout = QHBoxLayout()
button = QPushButton(text=QString('Push me!'))
layout.addWidget(button)
self.setLayout(layout)
button.clicked.connect(self.clicked.emit)
class Second(QWidget):
clicked = pyqtSignal()
def __init__(self, parent=None):
super(Second, self).__init__(parent)
layout = QHBoxLayout()
button = QPushButton(text=QString('Back to Start!'))
layout.addWidget(button)
self.setLayout(layout)
button.clicked.connect(self.clicked.emit)
app = QApplication(sys.argv)
myWindow = MainWindow(None)
myWindow.show()
app.exec_()
Can you help me and explain why print(str(self.parent())) returns MainWindow and self.print_base() returns QWidget? Where is parent() method defined? In super(ChildWidget, self).__init__(parent) parent goes to MainWindow init or in QWidget init?
import sys
from PySide import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.do_something() #sanity check
self.cw = ChildWidget(self)
self.setCentralWidget(self.cw)
self.show()
def do_something(self):
print 'doing something!'
class ChildWidget(QtGui.QWidget):
def print_base(self):
for base in self.__class__.__bases__:
print base.__name__
def __init__(self, parent):
super(ChildWidget, self).__init__(parent)
print(str(self.parent()))
self.print_base()
self.button1 = QtGui.QPushButton()
self.button1.clicked.connect(self.do_something_else)
self.button2 = QtGui.QPushButton()
self.button2.clicked.connect(self.parent().do_something)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.button1)
self.layout.addWidget(self.button2)
self.setLayout(self.layout)
self.show()
def do_something_else(self):
print 'doing something else!'
You are dealing with two types of hierarchy: 1) widgets hierary; 2) python classes hiearchy. The method "print_base" is listing all the base classes in a python POV, while "parent" returns the widget instance where the child widget is attached to.
I'm doing a GUI for a database through PyQt and Python. The main window (class Window) has a listbox where I put all my data, for this example I put "The program is working". Furthermore, The other window (class AddWin) help me to add new costumers to the database, but I couldn't modify the listbox from the class Addwin. I have the following code in my program and I would like to clean the listbox from the class AddWin, can you help me? or what is my mistake in the following code?
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
#Listbox
self.lista = QtGui.QListWidget(self)
self.lista.move(155,221)
self.lista.resize(855,455)
self.lista.addItem("The program is working")
class AddWin(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
main = Window()
main.lista.clear()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Your mistake is that code doesn't instantiate AddWin anywhere, so lista.clear is never called.
Your can test it by changing
window = Window()
to
window = AddWin()
LAST EDITED 21 / 8 / 2014 12 : 42
If your want to shard QtGui.QListWidget from QtGui.QMainWindow to QtGui.QDialog, Your can use pass value by reference to QtGui.QDialog.
Assume your QtGui.QMainWindow must have QtGui.QDialog (Or AddWin);
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
#Listbox
self.lista = QtGui.QListWidget(self)
self.lista.move(155,221)
self.lista.resize(855,455)
self.lista.addItem("The program is working")
self.myAddWin = AddWin(self.lista, self) # <- Pass QListWidget to your class
class AddWin(QtGui.QDialog):
def __init__(self, refQListWidget, parent=None):
QtGui.QDialog.__init__(self, parent)
self.myRefQListWidget = refQListWidget
self.myRefQListWidget.clear()