change label from other class in a different file - python

I am creating an application where I have a main window whit a label and then a docked widget that is in another file. I want to change the main windows label from a button at the docked widget. I try to import the main window file but then I can not access to the label. And I also tried to call a function in the main windows that changes the label but then the label does not change.
Here is the code:
main_window.py:
import results_window
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.define_main_windows()
self.create_dock_widgets()
def define_main_windows(self):
# Define de Main window properties
self.setMinimumSize(QSize(300, 100))
self.setWindowTitle("Python SkyLibris")
self.setWindowIcon(QtGui.QIcon("skylibris_icon.png"))
self.setStyleSheet("QMainWindow {background: 'white';}")
self.top = 50
self.left = 0
self.width = 1300
self.height = 400
self.setGeometry(self.left, self.top, self.width, self.height)
self.result = QLabel("result:")
self.setCentralWidget(self.result)
def create_dock_widgets(self):
# Create dock widgets
self.results_window = results_window.results_window()
self.resultsWindowDock = QDockWidget("Results Viewer", self)
self.resultsWindowDock.setWidget(self.results_window )
self.resultsWindowDock.setFloating(False)
self.resultsWindowDock.setVisible(True)
self.addDockWidget(Qt.LeftDockWidgetArea, self.resultsWindowDock)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())
results_window.py:
import main_window
class results_window(QWidget):
def __init__(self):
super(results_window, self).__init__()
print("init")
self.label = QLabel()
self.value = QLineEdit()
self.bt = QPushButton("Click")
self.bt.clicked.connect(self.clickMethod)
self.main_layout = QVBoxLayout()
self.main_layout.addWidget(self.label)
self.main_layout.addWidget(self.value)
self.main_layout.addWidget(self.bt)
self.setLayout(self.main_layout)
def clickMethod(self):
print(self.value.text())
text = self.value.text()
main_window.result.setText(text)

You are using the wrong tools, for example your code has a circular import that causes your application to close since it is equivalent to a while True.
In Qt, signals and slots are used to share data asynchronously, as well as contributing to the fact that there is no coupling between classes. In your case, Results_Window must have a signal that transmits that information to the MainWindow, this signal must be emit within clickMethod.
results_window.py
from PyQt5 import QtCore, QtWidgets
class Results_Window(QtWidgets.QWidget):
resultChanged = QtCore.pyqtSignal(str)
def __init__(self):
super(Results_Window, self).__init__()
print("init")
self.label = QtWidgets.QLabel()
self.value = QtWidgets.QLineEdit()
self.bt = QtWidgets.QPushButton("Click")
self.bt.clicked.connect(self.clickMethod)
main_layout = QtWidgets.QVBoxLayout(self)
main_layout.addWidget(self.label)
main_layout.addWidget(self.value)
main_layout.addWidget(self.bt)
#QtCore.pyqtSlot()
def clickMethod(self):
text = self.value.text()
self.resultChanged.emit(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
w = Results_Window()
w.show()
sys.exit(app.exec_())
main_window.py
from PyQt5 import QtCore, QtGui, QtWidgets
import results_window
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.define_main_windows()
self.create_dock_widgets()
def define_main_windows(self):
self.setMinimumSize(QtCore.QSize(300, 100))
self.setWindowTitle("Python SkyLibris")
self.setWindowIcon(QtGui.QIcon("skylibris_icon.png"))
self.setStyleSheet("QMainWindow {background: 'white';}")
top, left, width, height = 50, 0, 1300, 400
self.setGeometry(left, top, width, height)
self.result = QtWidgets.QLabel("result:")
self.setCentralWidget(self.result)
def create_dock_widgets(self):
self.results_window = results_window.Results_Window()
self.results_window.resultChanged.connect(self.result.setText)
self.resultsWindowDock = QtWidgets.QDockWidget("Results Viewer", self)
self.resultsWindowDock.setWidget(self.results_window )
self.resultsWindowDock.setFloating(False)
self.resultsWindowDock.setVisible(True)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.resultsWindowDock)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())

I had similar problem in PyQT5 where I was unable to access and set the local variables. After a lot of struggle I found writing to file and reading from file as the best solution. Simply write the desired output to file and access the same info from other file. Works great!

Related

PyQt5 custom widget split backghround?

I have had this happening multiple times. When I create a custom widget with an image in it all child widgets get seperated. How do I prevent that?
Full code that has the same outcome:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class CustomWidget(QWidget):
def __init__(self):
super(CustomWidget, self).__init__()
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.setStyleSheet(r'QWidget {background-color:#353634;}')
self.name_label = QLabel('name')
self.qty_label = QLabel('999')
self.image_pix = QPixmap(IMAGEPATH)
self.image_pix = self.image_pix.scaled(48, 48)
self.icon = QLabel()
self.icon.setPixmap(self.image_pix)
self.layout.addWidget(self.icon)
self.layout.addWidget(self.name_label)
self.layout.addWidget(self.qty_label)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.width, self.height = 425,350
self.resize(self.width, self.height)
custom_widget = CustomWidget()
self.setCentralWidget(custom_widget)
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec()
app.quit()

Display a dialog within the main window

The code below creates an empty dialog when Hello! is pressed:
from PyQt5 import QtWidgets, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
w = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
w.setLayout(layout)
self.setCentralWidget(w)
toyButton = QtWidgets.QPushButton("Hello!")
layout.addWidget(toyButton)
toyButton.clicked.connect(self.showdialog)
def showdialog(self):
d = QtWidgets.QDialog()
d.setWindowTitle("Dialog")
d.setWindowModality(QtCore.Qt.WindowModal)
d.exec_()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec_()
How can I force the dialog to appear within the main window instead of having it floating around as an independent window?
You simply need to give the dialog a parent widget: d = QtWidgets.QDialog(self.centralWidget()). self is also a valid parent; pick your favorite!
You could also add d to the layout: self.centralWidget().layout().addWidget(d);
although this second one does not respect your modality+exec.
Here's the full code comparing both methods:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
w = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout()
w.setLayout(layout)
self.setCentralWidget(w)
toyButton = QtWidgets.QPushButton("Hello!")
layout.addWidget(toyButton)
toyButton.clicked.connect(self.showdialog)
toyButton2 = QtWidgets.QPushButton("Hello2!")
layout.addWidget(toyButton2)
toyButton2.clicked.connect(self.showdialog2)
def showdialog(self):
d = QtWidgets.QDialog(self.centralWidget())
d.setWindowTitle("Dialog")
d.setWindowModality(QtCore.Qt.WindowModal)
d.exec_()
def showdialog2(self):
d = QtWidgets.QDialog()
d.setWindowTitle("Dialog2") # window title won't be seen...
d.setWindowModality(QtCore.Qt.WindowModal)
QtWidgets.QPushButton('Dialog2', parent=d) # ... so we add a little something
self.centralWidget().layout().addWidget(d)
d.exec_()

I can't get window to resize when I hide a widget

I found some code on here that shows an example of how you can get the window to resize when the widget is hidden, and it works for me. Here is the code:
from PyQt4 import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
self.app = QtGui.QApplication(sys.argv)
super(MainWindow, self).__init__()
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
self.layout = layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def startup(self):
self.show()
sys.exit(self.app.exec_())
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.resizeMe)
def resizeMe(self):
self.resize(self.minimumSizeHint())
if __name__ == "__main__":
myApp = MainWindow()
myApp.startup()
I then tried to modify this to match my existing code by separating the mainWindow class and the widget class. Here is the code that does that.
from PySide import QtGui,QtCore
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.w = testW(self)
self.setCentralWidget(self.w)
self.show()
class testW(QtGui.QWidget):
def __init__(self,parent):
super(testW,self).__init__()
self.parent = parent
self.button = QtGui.QPushButton('Show/Hide')
self.button.setCheckable(True)
self.button.setChecked(True);
self.frame = QtGui.QFrame()
self.frame.setFixedHeight(100)
self.layout = layout = QtGui.QVBoxLayout()
layout2 = QtGui.QVBoxLayout()
self.setLayout(layout)
self.frame.setLayout(layout2)
layout.addWidget(self.button)
layout.addWidget(self.frame)
layout.addStretch(1)
layout2.addWidget(QtGui.QLabel('Yoyoyo'))
self.button.toggled.connect(self.clickAction)
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.resizeMe)
def resizeMe(self):
self.resize(self.minimumSizeHint())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myApp = MainWindow()
sys.exit(app.exec_())
#time.sleep(1)
Running the first code does what I want it to. After I hide the widget, the window resizes to the correct size. The second implementation of the code does not shrink and expand the window when I hide and show the widget. Is this because the MainWindow is in a separate class?
Use size policies for your widgets. For your example you can change UI creation code as follows:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.w = testW(self)
self.w.setSizePolicy(
QtWidgets.QSizePolicy.MinimumExpanding,
QtWidgets.QSizePolicy.MinimumExpanding
)
self.setCentralWidget(self.w)
self.show()
Please note new setSizePolicy call which say Qt layout engine how to change the size of your widget according to its content.
Unfortunately QMainWindow does not respect sizeHint automatically, but it is calculated properly, so you can adjustSize manually:
def clickAction(self):
checked = self.button.isChecked()
if checked:
self.frame.show()
else:
self.frame.hide()
QtCore.QTimer.singleShot(0, self.parent.adjustSize)
You do not need to resize your widget itself, because it will be resized according to the policy. Even sizeHint will be calculated automatically so you need only to call adjustSize of QMainWindow.
PS: I used PySide2 instead of PySide so the imports are different a little bit:
from PySide2 import QtWidgets, QtCore

setting background image for a widget in another class

I've been recently learning pyqt5 as my first gui framework. So far I have been experimenting with QtStackedLayout. I currently have two window screens, one created inside the UI class and another in another separate class. I have two concerns:
Everything was working until I started experimenting on adding a background image for Window 1. There is no image displayed but the code runs ok.
There is this small fraction of time in the beginning where window one will get displayed first until it gets loaded to the mainwindow, I tried passing self during instantiation of the object to sert as some kind of parent to prevent this but I think I'm not doing it right.
See below code (I have bad import statements, I will sort it out)
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Ui(QWidget):
def setupUi(self, Main, width, height):
self.stack = QStackedLayout()
self.window_1 = WindowOne(width, height)
self.window_2 = QWidget(self)
self.window_2_UI()
self.stack.addWidget(self.window_1)
self.stack.addWidget(self.window_2)
# Only one button
self.btn = QPushButton("Change window", self)
# Create the central widget of your Main Window
self.main_widget = QWidget(self)
layout = QVBoxLayout(self.main_widget)
layout.addLayout(self.stack)
layout.addWidget(self.btn)
self.setCentralWidget(self.main_widget)
self.btn.clicked.connect(self.change_window)
def change_window(self):
if self.stack.currentIndex() == 0:
self.stack.setCurrentIndex(1)
else:
self.stack.setCurrentIndex(0)
def window_2_UI(self):
label = QLabel("In Window 2", self.window_2)
class WindowOne(QWidget):
def __init__(self, width, height):
super().__init__()
self.set_bg(width, height)
self.set_label()
# self.setStyleSheet("background-image: url(:resource/images/blue_bg.jpg)")
def set_label(self):
label = QLabel("In Window 1", self)
def set_bg(self, w, h):
oImage = QImage("resource/images/blue_bg.jpg")
sImage = oImage.scaled(QSize(w, h))
palette = QPalette()
palette.setBrush(10, QBrush(sImage))
self.setPalette(palette)
class Main(QMainWindow, Ui):
def __init__(self):
super().__init__()
self.w_width = 480
self.w_height = 720
self.resize(self.w_width, self.w_height)
self.init_ui()
self.setupUi(self, self.w_width, self.w_height)
def init_ui(self):
self.center()
self.setWindowTitle('Main Window')
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
if __name__ == "__main__":
app = QApplication(sys.argv)
M = Main()
M.show()
sys.exit(app.exec())
By default only the window (which is different to a widget) will use the background color of QPalette, if you want a widget to use the background color of QPalette you must enable the autoFillBackground property.
# ...
self.set_label(width, height)
self.setAutoFillBackground(True)
# ...
Although your code is a little messy, for example you establish that certain methods receive certain parameters but you never use them. Finally I think you want the background of the image to be re-scale using the size of the window so I have override the resizeEvent() method so that scaling takes the size of the window.
Considering all the above, I have improved your code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.m_stacked_layout = QtWidgets.QStackedLayout()
self.widget_1 = WidgetOne()
self.widget_2 = QtWidgets.QWidget()
self.widget_2_UI()
self.m_stacked_layout.addWidget(self.widget_1)
self.m_stacked_layout.addWidget(self.widget_2)
button = QtWidgets.QPushButton(
"Change window", clicked=self.change_window
)
lay = QtWidgets.QVBoxLayout(self)
lay.addLayout(self.m_stacked_layout)
lay.addWidget(button)
#QtCore.pyqtSlot()
def change_window(self):
ix = self.m_stacked_layout.currentIndex()
self.m_stacked_layout.setCurrentIndex(1 if ix == 0 else 0)
def widget_2_UI(self):
label = QtWidgets.QLabel("In Window 2", self.widget_2)
class WidgetOne(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setAutoFillBackground(True)
self.set_label()
self.m_image = QtGui.QImage("resource/images/blue_bg.jpg")
def set_label(self):
label = QtWidgets.QLabel("In Window 1", self)
def resizeEvent(self, event):
palette = self.palette()
sImage = self.m_image.scaled(event.size())
palette.setBrush(10, QtGui.QBrush(sImage))
self.setPalette(palette)
super(WidgetOne, self).resizeEvent(event)
class Main(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
widget = Widget()
self.setCentralWidget(widget)
self.resize(480, 720)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec())

How can I make a white box in PyQt?

I have a PyQt application that has a widget called Deck
class Deck(QtGui.QWidget):
def __init__(self, filename, parent):
super(Deck, self).__init__(parent)
self.setMinimumSize(100, 150)
self.setStyleSheet('background-color: white;')
label = QtGui.QLabel("deck", self)
label.show()
I expected the Deck widget to be all white, but it is only under the label, although it accepts clicks on its 100x150 area and adjusts its hbox:s size.
Edit:
The surrounding layout.
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
#import qt4reactor
#qt4reactor.install()
from deck import Deck
class Duel(QtGui.QWidget):
def __init__(self):
super(Duel, self).__init__()
topArea = QtGui.QHBoxLayout()
topArea.addStretch(1)
d = Deck(sys.argv[1], self)
d.show()
topArea.addWidget(d)
bottomArea = QtGui.QHBoxLayout()
d = Deck(sys.argv[2], self)
d.show()
bottomArea.addWidget(d)
bottomArea.addStretch(1)
vbox = QtGui.QVBoxLayout()
vbox.addLayout(topArea)
vbox.addStretch(1)
vbox.addLayout(bottomArea)
self.setLayout(vbox)
def main():
root = Duel()
root.show()
app.exec_()
if __name__ == '__main__':
main()

Categories