Call setCentralWidget from other file - python

I have different files (main.py and layout.py) and I want to change the windows (I have shortened the example that it should change the window size) of QMainWindow from the file layout.py.
It works fine from main.py, I can change the windows from the file main.py, but it has no effect in layout.py.
UPDATE: I changed the files two a working example with the problem that the Button "Switch to Layout 2" does not work.
main.py
import sys
from PyQt5.QtWidgets import QAction, QApplication, QMainWindow
from layout import Layout1, Layout2
class MainClass(QMainWindow):
def __init__(self):
super(MainClass, self).__init__()
def initUI(self):
self.setGeometry(50, 100, 600, 500)
self.setWindowTitle('program')
self.window1Action = QAction('Window1', self)
self.window1Action.triggered.connect(self.window1)
self.window2Action = QAction('Window2', self)
self.window2Action.triggered.connect(self.window2)
self.menubar = self.menuBar()
menu = self.menubar.addMenu('&Menu')
menu.addAction(self.window1Action)
menu.addAction(self.window2Action)
self.show()
def window1(self):
wsize1 = (1200, 600)
self.resize(*wsize1)
self.form_widget = Layout1()
self.setCentralWidget(self.form_widget)
def window2(self):
wsize2 = (600, 500)
self.resize(*wsize2)
self.form_widget = Layout2()
self.setCentralWidget(self.form_widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainClass()
ex.initUI()
sys.exit(app.exec_())
layout.py
from PyQt5.QtWidgets import QFormLayout, QPushButton, QWidget
class Layout1(QWidget):
def __init__(self, parent=None):
super(Layout1, self).__init__(parent)
self.form_layout = QFormLayout(self)
self.button1 = QPushButton('Button1')
self.form_layout.addRow('nonfunctional', self.button1)
self.buttonX = QPushButton('Switch to Layout2')
self.form_layout.addRow('Problem', self.buttonX)
self.buttonX.clicked.connect(self.change_layout)
self.setLayout(self.form_layout)
def change_layout(self):
from main import MainClass
self.change_window = MainClass()
self.change_window.window2()
class Layout2(QWidget):
def __init__(self, parent=None):
super(Layout2, self).__init__(parent)
self.form_layout = QFormLayout(self)
self.button2 = QPushButton('Button3')
self.form_layout.addRow('nonfunctional', self.button2)
self.setLayout(self.form_layout)
Can anybody explain to me what I have done wrong?

Your Layout classes have a parent parameter, so use it. You need to get a reference to the existing instance of the main window, not create a new one:
def window1(self):
...
self.form_widget = Layout1(self)
self.setCentralWidget(self.form_widget)
...
def change_layout(self):
self.parent().window2()

Related

How to have signals and slots connect across classes?

I am trying to make a basic text editor with a toolbar, sidebar, and textbox. My program needs to use a QPushButton (which is in my 'toolbar' class) to make the text in my QTextEdit bold (in my TextEdit class). Here's an example snippet of code:
import sys
from PyQt5.QtWidgets import QPushButton, QTextEdit, QWidget, QMainWindow
from PyQt5.Qt import Qt, QApplication, QVBoxLayout, QHBoxLayout, QFrame, QFont
class ToolBar(QWidget):
def __init__(self):
super().__init__()
layout = QHBoxLayout()
self.btn = QPushButton(self, text="Bold")
layout.addWidget(self.btn)
self.italic = QPushButton(self, text="Italic")
layout.addWidget(self.italic)
t = TextEdit()
# This is the line that isn't working
self.btn.clicked.connect(lambda: t.set_bold())
# I've tried this without the lambda, and also with 'TextEdit.set_bold' but they didn't work
# It would also be nice to do the same for the italic buttons and other buttons in my toolbar
self.setLayout(layout)
class TextEdit(QWidget):
def __init__(self):
super().__init__()
self.textEdit = QTextEdit(self)
# self.set_bold() <-- If I were to run this, then the text box would become bold, so I know that it's not an error with the function
def set_bold(self):
# print("function activated") <-- This statement shows that the function is indeed executing
self.font = QFont("Helvetica", 14)
self.font.setBold(True)
self.textEdit.setFont(self.font)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
central_widget = QFrame()
layout = QVBoxLayout()
self.boldButton = ToolBar()
layout.addWidget(self.boldButton)
self.textBox = TextEdit()
layout.addWidget(self.textBox)
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
I tried putting a print statement to confirm that the function is executing, which it is. I don't get any error messages so I can't seem to figure out what to do.
The connection must occur where the objects have a common scope, in this case within the MainWindow class.
class ToolBar(QWidget):
def __init__(self):
super().__init__()
self.bold_button = QPushButton(text="Bold")
self.italic_button = QPushButton(text="Italic")
layout = QHBoxLayout(self)
layout.addWidget(self.bold_button)
layout.addWidget(self.italic_button)
class TextEdit(QWidget):
def __init__(self):
super().__init__()
self.textEdit = QTextEdit(self)
def set_bold(self):
font = QFont("Helvetica", 14)
font.setBold(True)
self.textEdit.setFont(font)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.toolbar = ToolBar()
self.textBox = TextEdit()
central_widget = QFrame()
layout = QVBoxLayout(central_widget)
layout.addWidget(self.toolbar)
layout.addWidget(self.textBox)
self.setCentralWidget(central_widget)
self.toolbar.bold_button.clicked.connect(self.textBox.set_bold)

How can I inherit between classes in pyqt?

In order to track progress, this is the third question about practicing with different classes in PyQt5 .Here are the links to my previous questions:opening a new window, Open a file from main window to a new window in PyQt5 (in different files).
I'm trying to work with two classes, one with one button and when it's pressed it will load a file and show the text in a QTextEdit in other class.
In the first questions I was suggested that as an alternative to work with more classes, they can inherit from QMainWindow so I looked for more info for doing this: PyQt class inheritance
The second question code did worked but it would show both windows at the same time, so this question: PyQt: How to hide QMainWindow guided me to write this code (I attatch this here because it's a little bit different from the one in the link, plus I apply what it says in the answer):
import sys, os
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
class Dialog_02(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Dialog_02, self).__init__(parent, QtCore.Qt.Window)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
myBoxLayout = QVBoxLayout()
Button_02 = QPushButton ("Show Dialog 01")
myBoxLayout.addWidget(Button_02)
self.setLayout(myBoxLayout)
self.setWindowTitle('Dialog 02')
Button_02.clicked.connect(self.closeAndReturn)
def closeAndReturn(self):
self.close()
self.parent().show()
class Dialog_01(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Dialog_01, self).__init__()
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
myBoxLayout = QVBoxLayout()
Button_01 = QPushButton ("Show Dialog 02")
myBoxLayout.addWidget(Button_01)
self.setLayout(myBoxLayout)
self.setWindowTitle('Dialog 01')
Button_01.clicked.connect(self.callAnotherQMainWindow)
def callAnotherQMainWindow(self):
self.hide()
self.dialog_02 = Dialog_02(self)
self.dialog_02.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
sys.exit(app.exec_())
In this code I'm not inheriting, but it works fine.
The issue is that when I try to follow the same syntax in the original question code, it won't run, I'm not sure I'm getting inheritances fine.
import sys
import os
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QPushButton, QVBoxLayout, QTextEdit, QHBoxLayout, QLabel, QMainWindow, QAction, QFileDialog
class SecondWindow(QWidget):
def __init__(self, Window):
super(SecondWindow, self).__init__(parent, QtCore.Qt.Window)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.text = QTextEdit(self)
self.btn_return= QPushButton("Return")
self.init_ui()
def init_ui(self):
v_layout = QVBoxLayout(self)
v_layout.addWidget(self.text)
v_layout.addWidget(self.btn_return)
self.setLayout(v_layout)
self.setWindowTitle('Opened Text')
self.btn_return.clicked.connect(self.closeAndReturn)
def closeAndReturn(self):
self.close()
self.parent().show()
class Window(QMainWindow):
textChanged = QtCore.pyqtSignal(str)
def __init__(self, *args):
super(Window, self).__init__()
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.img = QLabel()
self.load_file= QPushButton('Load')
self.width = 400
self.height = 150
self.init_ui()
def init_ui(self):
self.img.setPixmap(QtGui.QPixmap("someimage.png"))
h_layout = QHBoxLayout()
v_layout = QVBoxLayout()
h_final = QHBoxLayout()
h_layout.addWidget(self.img)
v_layout.addWidget(self.load_file)
h_final.addLayout(h_layout)
h_final.addLayout(v_layout)
self.load_file.clicked.connect(self.loadafile)
self.setLayout(h_final)
self.setWindowTitle('Main Window')
self.setGeometry(600,150,self.width,self.height)
#QtCore.pyqtSlot()
def loadafile(self):
filename = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
with open(filename[0], 'r') as f:
file_text = f.read()
self.textChanged.emit(file_text)
self.hide()
self.dialog_02 = SecondWindow(self)
self.dialog_02.show()
def main():
app = QApplication(sys.argv)
main = Window()
s = SecondWindow(main)
main.textChanged.connect(s.text.append)
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You are coupling many classes: What happens if at a moment SecondWindow does not have a parent? Well, your code will have problems and you will have to modify it a lot so that it works correctly. So first it is to design the behavior of each class, for example SecondWindow has to warn the other windows that it was clicked, it has to have a method that updates the text. Similarly, Window must notify that there is new text available.
On the other hand QMainWindow already has a predefined layout so you must create a centralwidget where you place the other widgets.
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class SecondWindow(QtWidgets.QWidget):
closed = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(SecondWindow, self).__init__(parent, QtCore.Qt.Window)
self.text = QtWidgets.QTextEdit()
self.btn_return= QtWidgets.QPushButton("Return")
self.init_ui()
def init_ui(self):
v_layout = QtWidgets.QVBoxLayout(self)
v_layout.addWidget(self.text)
v_layout.addWidget(self.btn_return)
self.setWindowTitle('Opened Text')
self.btn_return.clicked.connect(self.close)
self.btn_return.clicked.connect(self.closed)
#QtCore.pyqtSlot(str)
def update_text(self, text):
self.text.setText(text)
self.show()
class Window(QtWidgets.QMainWindow):
textChanged = QtCore.pyqtSignal(str)
def __init__(self, *args):
super(Window, self).__init__()
self.img = QtWidgets.QLabel()
self.load_file= QtWidgets.QPushButton('Load')
self.width = 400
self.height = 150
self.init_ui()
def init_ui(self):
self.img.setPixmap(QtGui.QPixmap("someimage.png"))
self.load_file.clicked.connect(self.loadafile)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
h_layout = QtWidgets.QHBoxLayout(central_widget)
h_layout.addWidget(self.img)
h_layout.addWidget(self.load_file)
self.setWindowTitle('Main Window')
self.setGeometry(600,150,self.width,self.height)
#QtCore.pyqtSlot()
def loadafile(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
if filename:
with open(filename, 'r') as f:
file_text = f.read()
self.textChanged.emit(file_text)
self.close()
def main():
app = QtWidgets.QApplication(sys.argv)
main = Window()
s = SecondWindow()
main.textChanged.connect(s.update_text)
s.closed.connect(main.show)
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Click a button to change a GIF

In the App there are a QButton and a QLabel. In the QLabel I put a QMovie in, to show a GIF. By clicking the QButton I want to change the GIF, which path is defined in a list.
The problem: the App shows only the first GIF. The Button seems not working. What have I done wrong?
But: Please dont change the structure of the code. E.g. I want to have the QLabel defined in the sub-function and return from there the QLabel.
The code:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import random
list = ['F:\\test1.gif', 'F:\\test2.gif', 'F:\\test3.gif', 'F:\\test4.gif']
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.resize(600, 600)
self.initUI()
def initUI(self):
self.btn = QPushButton("change", self)
self.btn.clicked.connect(self.changeGIF)
self.grid = QVBoxLayout()
self.grid.addWidget(self.btn)
self.grid.addWidget(self.changeGIF())
self.grid.addStretch(1)
self.setLayout(self.grid)
def changeGIF(self):
randomValue = list[random.randint(1, len(list)-1)]
print(randomValue)
self.lbl = QLabel()
self.gif = QMovie(randomValue)
self.lbl.setMovie(self.gif)
self.gif.start()
return self.lbl
if __name__ == '__main__':
app = QApplication(sys.argv)
MyApp = Window()
MyApp.show()
sys.exit(app.exec_())
Thanks for the help!
since the QLabel will be responsible for showing GIFs in a random way, it is advisable to create a class that only takes care of that task, in this widget you must have a method that changes the QMovie of the QLabel.
list_of_gifs = ['F:\\test1.gif', 'F:\\test2.gif', 'F:\\test3.gif', 'F:\\test4.gif']
class GIFLabel(QLabel):
def __init__(self, gifs, *args, **kwargs):
QLabel.__init__(self, *args, **kwargs)
self.mGifs = gifs
self.changeGIF()
def changeGIF(self):
gif = random.choice(self.mGifs)
movie = QMovie(gif)
self.setMovie(movie)
movie.start()
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.resize(600, 600)
self.initUI()
def initUI(self):
self.btn = QPushButton("change", self)
self.label = GIFLabel(list_of_gifs, self)
self.btn.clicked.connect(self.label.changeGIF)
self.grid = QVBoxLayout(self)
self.grid.addWidget(self.btn)
self.grid.addWidget(self.label)
self.grid.addStretch(1)
if __name__ == '__main__':
app = QApplication(sys.argv)
MyApp = Window()
MyApp.show()
sys.exit(app.exec_())

How to make a widget attached to QTabWidget's gap and move accordingly with QSplitter in pyqt5

I want to make the button always next to the second tab's label, even when I use splitter to move the edge between two tabs. How to achieve that? I believe it's because I use the absolute position, but how make an widget attached in the gap in QTabWidget?
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QFrame,
QSplitter, QStyleFactory, QApplication,QTabWidget,QPushButton)
from PyQt5.QtCore import Qt
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
tab1 = QTabWidget(self)
tab2 = QTabWidget(self)
a=QWidget()
a.setGeometry(0,0, 40, 40)
tab2.addTab(a,"2")
splitter1 = QSplitter(Qt.Vertical)
splitter1.addWidget(tab1)
splitter1.addWidget(tab2)
splitter1.setSizes([100,100])
hbox.addWidget(splitter1)
self.setLayout(hbox)
z=QPushButton(self)
z.setGeometry(100,100,70,20)
z.setText("button")
self.setGeometry(300, 300, 300, 200)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
This is what I want to achieve all the time.
This is what happened when I adjust the edge between two tabs.
When you add a parent to a widget, the widget has a coordinate system relative to the parent, so you must change the parent. In addition to adjusting the position of the button to one relative to the parent:
[...]
z=QPushButton(tab2)
z.setGeometry(100,0,70,20)
z.setText("button")
[...]
Another series improvement that even if the size of the QtabWidget changes, the button remains centered:
class TabWidgetWithButton(QTabWidget):
def __init__(self, *args, **kwargs):
QTabWidget.__init__(self, *args, **kwargs)
self.button = QPushButton("button", self)
def resizeEvent(self, event):
self.button.move((self.width()-self.button.width())/2, 0)
QTabWidget.resizeEvent(self, event)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
hbox = QHBoxLayout(self)
tab1 = QTabWidget(self)
tab2 = TabWidgetWithButton(self)
a=QWidget(self)
tab2.addTab(a,"2")
splitter1 = QSplitter(Qt.Vertical)
splitter1.addWidget(tab1)
splitter1.addWidget(tab2)
splitter1.setSizes([100,100])
hbox.addWidget(splitter1)
self.setLayout(hbox)
self.setGeometry(300, 300, 300, 200)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

Add different text to a window

I have a button and a text label. Each time the button is pressed, i would like text placed from a line edit to be placed onto the window. So far I can only get one text to draw onto the window, even if I create another textlabel. Ive tried seeting a click count determining how many times a user has clicked a button but this doesnt work either. Heres what I have so far, any suggestions?
import sys
import os
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtGui import QApplication
class Window(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.centralWidget = QWidget(self)
self.setCentralWidget(self.centralWidget)
self.setGeometry(450,100,350,680)
self.btn1 = QPushButton("Enter", self.centralWidget)
self.btn1.setGeometry(10,50,150, 20)
self.btn1.clicked.connect(self.enter)
self.edit = QtGui.QLineEdit(self)
self.edit.setGeometry(10, 10, 150, 20)
self.label = QtGui.QLabel(self)
self.label.setGeometry(240, 170,150, 20)
def enter(self):
self.label.setText(self.edit.text())
def main(args):
global app
app = App(args)
app.exec_()
class App(QApplication):
def __init__(self, *args):
QApplication.__init__(self, *args)
self.main = Window()
self.connect(self, SIGNAL("lastWindowClosed()"), self.byebye )
self.main.show()
def byebye( self ):
self.exit(0)
if __name__ == "__main__":
main(sys.argv)
There are a few problems with your example code, the main one being that you are trying to manually arrange the widgets, rather than using a layout.
It's hard to tell from your question exactly what you expect the output to be, so I've assumed you want the text from line-edit to be appended to the label, so that you end up with a series of lines.
Here's a simplified version of your example that hopefully does what you want:
from PyQt4 import QtCore, QtGui
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.btn1 = QtGui.QPushButton("Enter", self)
self.btn1.clicked.connect(self.enter)
self.edit = QtGui.QLineEdit(self)
self.label = QtGui.QLabel(self)
self.label.setAlignment(
QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
widget = QtGui.QWidget(self)
layout = QtGui.QVBoxLayout(widget)
layout.addWidget(self.edit)
layout.addWidget(self.btn1)
layout.addWidget(self.label)
self.setCentralWidget(widget)
def enter(self):
text = self.edit.text()
if text:
self.label.setText('%s\n%s' % (self.label.text(), text))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(450, 100, 350, 680)
window.show()
sys.exit(app.exec_())

Categories

Resources