To Use Class Variable of the Main Window in Other Window, PyQt5 - python

I have two QWidget windows as in the pictures. The first picture where I get the input of the variable, the other picture where I process the variable to show the user. However, I did not manage to use the variable in the other class (QWidget). To summarize it ;
This is the window I have entered my data.
This is the second window and class where I want to process and show the result. I need to use the variable defined in the first class. I have a calculation function in the second class that does the calculation like 2math. piMain. Diameter. Then I need to recall this function to show the result again.
You can find the all code below.
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
import sys
import math
from PyQt5.QtGui import QPixmap,QFont
import sqlite3
class Main(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Calculation")
self.setGeometry(450,100,1250,600)
self.UI()
self.show()
def UI(self):
self.mainDesign()
self.layouts()
def mainDesign(self):
self.setStyleSheet('background-color:white')
#CUSTOMER INFORMATION BUTTONS AND TEXT###
#### CALCULATE BUTTONS###
self.buttonCalcBillet = QPushButton("Calculate")
self.buttonCalcBillet.setStyleSheet(
'background-color: orange;'
'color: black;'
)
### CALCULATE BUTTONS CLICKED ###
self.buttonCalcBillet.clicked.connect(self.billetCalculationResults)
######
self.Title = QLabel("Some Maths")
self.Title.setAlignment(QtCore.Qt.AlignHCenter)
self.Title.setStyleSheet('font-size: 18pt; font-family: arial,sans-serif')
self.DiameterLabel = QLabel("Diameter")
self.DiameterLabel.setStyleSheet('font-size: 12pt; font-family: arial,sans-serif')
self.DiameterQline = QLineEdit()
self.DiameterQline.setPlaceholderText("Please Enter Diameter in mm")
self.DiameterQline.setStyleSheet(
'font-family:Hack,monospace;'
'font:12px;'
'mind-width:20em;'
)
def layouts(self):
#####LAYOUTS#########
self.mainLayout = QHBoxLayout()
self.billetLayout = QFormLayout()
###ADDING CHILD LAYOUTS TO MAIN LAYOUTS######
self.mainLayout.addLayout(self.billetLayout,350)
###CALCULATION BUTTON WIDGETS###
self.billetLayout.addRow(self.Title)
self.billetLayout.addRow(self.DiameterLabel, self.DiameterQline)
self.billetLayout.addRow(self.buttonCalcBillet)
####SETTING MAIN LAYOUT###
self.setLayout(self.mainLayout)
def billetCalculationResults(self):
self.billetCalculation = BilletCalculationResults()
self.GetValues()
self.close()
def GetValues(self):
self.Diameter = float(self.DiameterQline.text())
class BilletCalculationResults(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Calculation Results")
self.setGeometry(450,150,350,600)
####CONSTRUCTION OF THE FIRST BILLET CLASS ###
self.UI()
self.show()
def UI(self):
self.billetCalculationPageDesign()
self.billetCalculationLayouts()
def billetCalculationPageDesign(self):
### BILLET RESULTS OF CALCULATION PAGE DESIGN ###
self.billetCalSurfaceAreaLabel = QLabel("Surface Area : ")
self.billetCalSurfaceAreaLabel.setStyleSheet('font-size: 12pt; font-family: arial,sans-serif')
self.billetCalSurfaceAreaLabelResult = QLabel(" : ")
self.billetCalSurfaceAreaLabelResult.setStyleSheet('font-size: 12pt; font-family: arial,sans-serif')
def billetCalculationLayouts(self):
## BILLET RESULTS OF CALCULATION PAGE DESIGN ###
self.billetMainLayout = QFormLayout()
self.billetMainLayout.addRow(self.billetCalSurfaceAreaLabel,self.billetCalSurfaceAreaLabelResult)
self.setLayout(self.billetMainLayout)
##def calculation():
## Something like : return Main.Diameter * 2 * math.pi
def main():
APP = QApplication(sys.argv)
window = Main()
sys.exit(APP.exec())
if __name__== '__main__':
main()

To pass and argument to another class you can pass it like this:
self.billetCalculation = BilletCalculationResults(self.GetValues())
And to use it in class BilletCalculationResult init method like this:
def __init__(self, diameter):
self.diameter = diameter
Full code below:
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
import sys
import math
from PyQt5.QtGui import QPixmap, QFont
import sqlite3
class Main(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Calculation")
self.setGeometry(450, 100, 1250, 600)
self.UI()
self.show()
def UI(self):
self.mainDesign()
self.layouts()
def mainDesign(self):
self.setStyleSheet('background-color:white')
# CUSTOMER INFORMATION BUTTONS AND TEXT###
#### CALCULATE BUTTONS###
self.buttonCalcBillet = QPushButton("Calculate")
self.buttonCalcBillet.setStyleSheet(
'background-color: orange;'
'color: black;'
)
### CALCULATE BUTTONS CLICKED ###
self.buttonCalcBillet.clicked.connect(self.billetCalculationResults)
######
self.Title = QLabel("Some Maths")
self.Title.setAlignment(QtCore.Qt.AlignHCenter)
self.Title.setStyleSheet('font-size: 18pt; font-family: arial,sans-serif')
self.DiameterLabel = QLabel("Diameter")
self.DiameterLabel.setStyleSheet('font-size: 12pt; font-family: arial,sans-serif')
self.DiameterQline = QLineEdit()
self.DiameterQline.setPlaceholderText("Please Enter Diameter in mm")
self.DiameterQline.setStyleSheet(
'font-family:Hack,monospace;'
'font:12px;'
'mind-width:20em;'
)
def layouts(self):
#####LAYOUTS#########
self.mainLayout = QHBoxLayout()
self.billetLayout = QFormLayout()
###ADDING CHILD LAYOUTS TO MAIN LAYOUTS######
self.mainLayout.addLayout(self.billetLayout, 350)
###CALCULATION BUTTON WIDGETS###
self.billetLayout.addRow(self.Title)
self.billetLayout.addRow(self.DiameterLabel, self.DiameterQline)
self.billetLayout.addRow(self.buttonCalcBillet)
####SETTING MAIN LAYOUT###
self.setLayout(self.mainLayout)
def billetCalculationResults(self):
self.billetCalculation = BilletCalculationResults(self.GetValues())
self.close()
def GetValues(self):
return float(self.DiameterQline.text())
class BilletCalculationResults(QWidget):
def __init__(self, diameter):
self.diameter = diameter
super().__init__()
self.setWindowTitle("Calculation Results")
self.setGeometry(450, 150, 350, 600)
####CONSTRUCTION OF THE FIRST BILLET CLASS ###
self.UI()
self.show()
def UI(self):
self.billetCalculationPageDesign()
self.billetCalculationLayouts()
def billetCalculationPageDesign(self):
### BILLET RESULTS OF CALCULATION PAGE DESIGN ###
print(self.calculation())
self.billetCalSurfaceAreaLabel = QLabel("Surface Area : ")
self.billetCalSurfaceAreaLabel.setStyleSheet('font-size: 12pt; font-family: arial,sans-serif')
self.billetCalSurfaceAreaLabelResult = QLabel(f"{str(self.calculation())}")
self.billetCalSurfaceAreaLabelResult.setStyleSheet('font-size: 12pt; font-family: arial,sans-serif')
def billetCalculationLayouts(self):
## BILLET RESULTS OF CALCULATION PAGE DESIGN ###
self.billetMainLayout = QFormLayout()
self.billetMainLayout.addRow(self.billetCalSurfaceAreaLabel, self.billetCalSurfaceAreaLabelResult)
self.setLayout(self.billetMainLayout)
def calculation(self):
return self.diameter * 2 * math.pi
def main():
APP = QApplication(sys.argv)
window = Main()
sys.exit(APP.exec())
if __name__ == '__main__':
main()

Related

Background disappearing when changing stylesheet after qthread

After making a few interfaces using the PySide6 library I keep having this issue where the custom background that I initialize turns black when calling a setStyleSheet statement after the program has gone through a qthread process.
This is how I initialize the background:
background = QPixmap("Data\\background.png")
palette = QPalette()
palette.setBrush(QPalette.Window, background)
self.show()
self.setPalette(palette)
And this is how I make the qthread:
class Signaller(QObject):
progress = Signal(int)
finished = Signal()
class Generate(QThread):
def __init__(self):
QThread.__init__(self)
self.signaller = Signaller()
def run(self):
self.signaller.progress.emit(0)
#do stuff
self.signaller.progress.emit(1)
self.signaller.finished.emit()
class Main(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setEnabled(False)
QApplication.processEvents()
self.progressBar = QProgressDialog("Generating...", None, 0, 1, self)
self.progressBar.setWindowTitle("Status")
self.progressBar.setWindowModality(Qt.WindowModal)
self.worker = Generate()
self.worker.signaller.progress.connect(self.set_progress)
self.worker.signaller.finished.connect(self.patch_finished)
self.worker.start()
def set_progress(self, progress):
self.progressBar.setValue(progress)
def patch_finished(self):
box = QMessageBox(self)
box.setWindowTitle("Done")
box.setText("Mod generated !")
box.exec()
self.setEnabled(True)
Yet calling this statement after the program's gone through the qthread at least once removes the background:
self.seed_field.setStyleSheet("color: #ffffff")
And it doesn't happen if the qthread hasn't triggered beforehand
Here is a fully working example:
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
import sys
class Signaller(QObject):
progress = Signal(int)
finished = Signal()
class Generate(QThread):
def __init__(self):
QThread.__init__(self)
self.signaller = Signaller()
def run(self):
self.signaller.progress.emit(0)
#do stuff
self.signaller.progress.emit(1)
self.signaller.finished.emit()
class Main(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setStyleSheet("QWidget{background:transparent; color: #ffffff; font-family: Cambria; font-size: 18px}"
+ "QMessageBox{background-color: #1d1d1d}"
+ "QDialog{background-color: #1d1d1d}"
+ "QProgressDialog{background-color: #1d1d1d}"
+ "QPushButton{background-color: #1d1d1d}"
+ "QSpinBox{background-color: #1d1d1d}"
+ "QLineEdit{background-color: #1d1d1d}"
+ "QLineEdit[text=\"\"]{color: #666666}"
+ "QMenu{background-color: #1d1d1d}"
+ "QToolTip{border: 0px; background-color: #1d1d1d; color: #ffffff; font-family: Cambria; font-size: 18px}")
grid = QGridLayout()
grid.setSpacing(10)
box_1_grid = QGridLayout()
self.box_1 = QGroupBox("Test")
self.box_1.setLayout(box_1_grid)
grid.addWidget(self.box_1, 0, 0, 1, 1)
button_1 = QPushButton("QThread")
button_1.clicked.connect(self.button_1_pressed)
box_1_grid.addWidget(button_1, 0, 0)
button_2 = QPushButton("StyleSheet")
button_2.clicked.connect(self.button_2_pressed)
box_1_grid.addWidget(button_2, 0, 1)
self.setLayout(grid)
self.setFixedSize(1280, 720)
background = QPixmap("background.png")
palette = QPalette()
palette.setBrush(QPalette.Window, background)
self.show()
self.setPalette(palette)
center = QScreen.availableGeometry(QApplication.primaryScreen()).center()
geo = self.frameGeometry()
geo.moveCenter(center)
self.move(geo.topLeft())
QApplication.processEvents()
def button_1_pressed(self):
self.setEnabled(False)
QApplication.processEvents()
self.progressBar = QProgressDialog("Generating...", None, 0, 1, self)
self.progressBar.setWindowTitle("Status")
self.progressBar.setWindowModality(Qt.WindowModal)
self.worker = Generate()
self.worker.signaller.progress.connect(self.set_progress)
self.worker.signaller.finished.connect(self.patch_finished)
self.worker.start()
def button_2_pressed(self):
self.box_1.setStyleSheet("color: #ffffff")
def set_progress(self, progress):
self.progressBar.setValue(progress)
def patch_finished(self):
box = QMessageBox(self)
box.setWindowTitle("Done")
box.setText("QThread done")
box.exec()
self.setEnabled(True)
def main():
app = QApplication(sys.argv)
main = Main()
sys.exit(app.exec())
if __name__ == '__main__':
main()
I had a similar problem, I solved it by setting the background not with a pixel, but with some_object.setStyleSheet(background: url("some/url")

How to keep a window open in Python PyQt

I am trying to build a python based software. (PYQT based software)
Issue:
My second window keeps closing when right after it opens.
Questions:
Is there something wrong with my code?
how do I fix it?
Note: The second window opens when the start button is clicked.
Here is my code:
class MainWindow(QMainWindow):
switch_window=pyqtSignal(str)
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#Initialize
self.setGeometry(1000, 300, 1200, 800)
self.setWindowTitle('Sensorlyze')
self.setWindowIcon(QIcon('biosensor.jpg'))
icon = QIcon('biosensor.jpg')
# Add Text
l1= QLabel("Welcome to SensorLyze",self)
l1.move(25, 350)
# l1.setWordWrap(True)
l1.setFont(QFont('Calibri',15))
l1.adjustSize()
l2 = QLabel("A software to simply sensor analytics", self)
l2.move(25, 400)
l2.setFont(QFont('Calibri', 10))
l2.adjustSize()
#Add Buttons
button1 = QPushButton('Start',self)
button1.resize(button1.sizeHint())
button1.clicked.connect(start_clicked)
button1.move(60, 450)
button2 = QPushButton('Exit', self)
button2.resize(button2.sizeHint())
button2.clicked.connect(exit_clicked)
button2.move(240, 450)
stylesheet = """
QMainWindow {
background-image: url("C:/Users/admin/Desktop/Sensorlyze/biosensor.jpg");
background-repeat: no-repeat;
background-position: center;
}
"""
# def switch(self):
# self.switch_window.emit(self.line_edit.text())
def start_clicked():
window=QMainWindow()
window.setGeometry(300, 500, 500, 500)
window.setWindowTitle('Hello')
window.show()
win.hide()
def exit_clicked():
msgBox=QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("Are you sure you want to exit?")
msgBox.setWindowTitle("Exit Sensorlyze")
msgBox.setStandardButtons(QMessageBox.Ok|QMessageBox.Cancel)
msgBox.buttonClicked.connect(msgButtonClick)
returnValue = msgBox.exec()
if returnValue==QMessageBox.Ok:
exit()
def msgButtonClick(i):
print("Buttonclickedis:",i.text())
def main():
app = QApplication(sys.argv)
app.setStyleSheet(stylesheet) # <---
win=MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Am I missing something here? Any help...
Alec answered the question but if you are still unclear here is corrected code.
import sys
from PyQt5.QtWidgets import QMainWindow, QLabel, QPushButton, QMessageBox, QApplication
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtGui import QIcon, QFont
class MainWindow(QMainWindow):
switch_window=pyqtSignal(str)
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
#Initialize
self.setGeometry(1000, 300, 1200, 800)
self.setWindowTitle('Sensorlyze')
self.setWindowIcon(QIcon('biosensor.jpg'))
icon = QIcon('biosensor.jpg')
# Add Text
l1= QLabel("Welcome to SensorLyze",self)
l1.move(25, 350)
# l1.setWordWrap(True)
l1.setFont(QFont('Calibri',15))
l1.adjustSize()
l2 = QLabel("A software to simply sensor analytics", self)
l2.move(25, 400)
l2.setFont(QFont('Calibri', 10))
l2.adjustSize()
#Add Buttons
button1 = QPushButton('Start',self)
button1.resize(button1.sizeHint())
button1.clicked.connect(self.start_clicked)
button1.move(60, 450)
button2 = QPushButton('Exit', self)
button2.resize(button2.sizeHint())
button2.clicked.connect(self.exit_clicked)
button2.move(240, 450)
def start_clicked(self):
self.window = QMainWindow()
self.window.setGeometry(300, 500, 500, 500)
self.window.setWindowTitle('Hello')
self.window.show()
# win.hide()
def exit_clicked(self):
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("Are you sure you want to exit?")
msgBox.setWindowTitle("Exit Sensorlyze")
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msgBox.buttonClicked.connect(self.msgButtonClick)
returnValue = msgBox.exec()
if returnValue == QMessageBox.Ok:
exit()
def msgButtonClick(self, i):
print("Buttonclickedis:", i.text())
stylesheet = """
QMainWindow {
background-image: url("C:/Users/admin/Desktop/Sensorlyze/biosensor.jpg");
background-repeat: no-repeat;
background-position: center;
}
"""
# def switch(self):
# self.switch_window.emit(self.line_edit.text())
def main():
app = QApplication(sys.argv)
app.setStyleSheet(stylesheet) # <---
win=MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

How to Set Back Ground Color of text occupied area alone in QLabel?

How to set a background colour of text occupied area Only, in QLabel ?
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class myList(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Frame Example")
self.myui()
def myui(self):
self.textbox = QLineEdit()
self.label_head = QLabel("Company Name")
self.textbox.setFixedSize(400,30)
self.label_head.setFont(QFont("caliber",12,QFont.Bold))
self.label_head.setAlignment(Qt.AlignCenter)
self.label_head.setStyleSheet("background-color:red;border-radius:5px;padding:2px;")
self.label_head.adjustSize()
self.label_head.setAutoFillBackground(True)
vbox = QVBoxLayout()
vbox.addWidget(self.label_head)
vbox.addWidget(self.textbox)
self.setLayout(vbox)
def main():
myapp = QApplication(sys.argv)
mywin = myList()
mywin.show()
sys.exit(myapp.exec_())
if __name__ == '__main__':
main()
In this code, I need a background color to text area only ( "Company name").
Try it
self.label_head = QLabel("<span style='color: #fff; background-color: #00f'>Company Name</span>")
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class myList(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Frame Example")
self.myui()
def myui(self):
self.textbox = QLineEdit()
self.label_head = QLabel("<span style='color: #fff; background-color: #00f'>Company Name</span>") # <---
self.textbox.setFixedSize(400,30)
self.label_head.setFont(QFont("caliber",12,QFont.Bold))
self.label_head.setAlignment(Qt.AlignCenter)
self.label_head.setStyleSheet("background-color:red;border-radius:5px;padding:2px;")
self.label_head.adjustSize()
self.label_head.setAutoFillBackground(True)
vbox = QVBoxLayout()
vbox.addWidget(self.label_head)
vbox.addWidget(self.textbox)
self.setLayout(vbox)
def main():
myapp = QApplication(sys.argv)
mywin = myList()
mywin.show()
sys.exit(myapp.exec_())
if __name__ == '__main__':
main()

PyQt5 Mouse Tracking Over QLabel Object

I am using PyQt5 to create an application. The application has a MainWindow with several widgets. One of the widgets is a QLabel object that displays a video. I want to track the cursor and display the cursor coordinates as I mouse over the video when I check a radio button.
I created a MouseTracking class that I’m passing the QLabel object into as window. I have verified that the passed into the class by printing its geometry. But I’m somehow not associating the mouse tracking to window. Here is the code for the MouseTracking class. What am I doing wrong?
class MouseTracker(QLabel):
def __init__(self, window):
super().__init__(window)
self.window = window
self.window.setMouseTracking(True)
self.initUI()
def initUI(self):
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet('background-color: white; border: 1px solid black')
self.show()
def mouseMoveEvent(self, event):
x = event.x()
y = event.y()
print("X, Y = ", x, y)
self.label.setGeometry(x+30, y-15, 90, 40)
self.label.setText('(%d, %d)' % (x, y))
In your code you have enabled the mouseTracking property of the "window" but you are monitoring the mouseMoveEvent method of the MouseTracker which is incorrect. If you want to track the events of a widget without overriding any method then you must use an event filter.
In the following example I try to implement your application based on your description, for example the green QLabel represents the QLabel that the video shows. Considering the above, the solution is as follows:
from PyQt5 import QtCore, QtGui, QtWidgets
class MouseTracker(QtCore.QObject):
positionChanged = QtCore.pyqtSignal(QtCore.QPoint)
def __init__(self, widget):
super().__init__(widget)
self._widget = widget
self.widget.setMouseTracking(True)
self.widget.installEventFilter(self)
#property
def widget(self):
return self._widget
def eventFilter(self, o, e):
if o is self.widget and e.type() == QtCore.QEvent.MouseMove:
self.positionChanged.emit(e.pos())
return super().eventFilter(o, e)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
self.video_label = QtWidgets.QLabel()
self.video_label.setStyleSheet("background-color: green; border: 1px solid black")
tracker = MouseTracker(self.video_label)
tracker.positionChanged.connect(self.on_positionChanged)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.video_label)
lay.addWidget(QtWidgets.QLabel())
self.resize(640, 480)
self.label_position = QtWidgets.QLabel(
self.video_label, alignment=QtCore.Qt.AlignCenter
)
self.label_position.setStyleSheet('background-color: white; border: 1px solid black')
#QtCore.pyqtSlot(QtCore.QPoint)
def on_positionChanged(self, pos):
delta = QtCore.QPoint(30, -15)
self.label_position.show()
self.label_position.move(pos + delta)
self.label_position.setText("(%d, %d)" % (pos.x(), pos.y()))
self.label_position.adjustSize()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Adjust widths of QHBoxLayout

Here is the code:
#!/usr/bin/env python3
import sys, time
from PySide import QtCore, QtGui
import base64
# Usage: Toast('Message')
class Toast(QtGui.QDialog):
def __init__(self, title, msg, duration=2):
QtGui.QDialog.__init__(self)
self.duration = duration
self.title_label = QtGui.QLabel(title)
self.title_label.setAlignment(QtCore.Qt.AlignLeft)
self.msg_label = QtGui.QLabel(msg)
self.icon_button = QLabelButton()
img_b64 = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAITgAACE4BjDEA7AAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAABJdEVYdENvcHlyaWdodABQdWJsaWMgRG9tYWluIGh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL3B1YmxpY2RvbWFpbi9Zw/7KAAAB2ElEQVRIibWVPW/TUBiFz7mJTBFSGgnUqmABRgpMUYi53pCK1IWxUxd2BgYk/goDAzuq+AFILEhIZUuq/ACPrYRKGSJPdHkPQx3UOK7tJOKd7Guf57nXH++lJFRVr9e70el03pLcBnAnH/4t6SzLsvdpml5U5duVdABhGDLLsj6AjSvD9wFshWHIujzrVgBcrqLb7b6U9AoASH6aTqdf62YPAK6WDiBN0wszO52dm9lpEzhQs4LhcNhzzj13zj2TtDUXJH+Z2bGZ/ZhMJulSApL03r+WtNdoluS38Xj8USWw0kcUx/F+UzgASNqL43i/7NqCwHu/A+CgKfxKHeTZagGAPsnWsvQ8028ieLIsvCq7IJD0eFV6WXZO4L3fzFvCSkVy23u/ea2A5KNV4dcx5gRm9nBdQZFRfAcP1hUUGXMC59zagiLjn2AwGNwCsPCjrFA7OWteEATBrqRG3bWqJLkgCHZn523gsrnFcdwi+YXkrGEJAMxMs+OSonNutukwF9DMWiQpSUyS5Kmku+vOvKzM7KxtZu8A3PwfAgB/2iQ/m9m9qrtIxgBuF4bPJY1qBD8b7clJkryQ9KYg/TAajb7XZRt9NVEUHUk6BHAC4ETSYRRFR02yfwEMBLRPQVtfqgAAAABJRU5ErkJggg=="
pixmap = QtGui.QPixmap()
pixmap.loadFromData(base64.b64decode(img_b64))
self.icon_button.setPixmap(pixmap)
self.icon_button.resize(20, 20)
self.connect(self.icon_button, QtCore.SIGNAL("clicked()"), self.close)
title_layout = QtGui.QVBoxLayout()
title_layout.addWidget(self.title_label)
title_layout.addWidget(self.msg_label)
layout = QtGui.QHBoxLayout()
layout.addWidget(self.icon_button)
layout.addLayout(title_layout)
self.setGeometry(0, 0, 200, 70)
self.setLayout(layout)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
# self.setStyleSheet("border: 1px solid red; border-radius: 5px;")
self.toastThread = ToastThread(self.duration)
self.toastThread.finished.connect(self.close)
self.toastThread.start()
class ToastThread(QtCore.QThread):
def __init__(self, n_seconds):
QtCore.QThread.__init__(self)
self.n_seconds = n_seconds
def run(self):
time.sleep(self.n_seconds)
class QLabelButton(QtGui.QLabel):
def __init(self, parent):
QLabel.__init__(self, parent)
def mouseReleaseEvent(self, ev):
self.emit(QtCore.SIGNAL('clicked()'))
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
program = Toast("hi", "there", 10)
program.show()
sys.exit(app.exec_())
Apparent the image label on the left is taking too much space. How can I fix this?
A horizontal layout will give each widget an equal amount of space by default, but you can adjust the ratio like this:
layout.addWidget(self.icon_button, 1)
layout.addLayout(title_layout, 3)
So that gives the title three times as much space as the icon.
This should work, just add:
self.icon_button.setFixedWidth(30)
by default it seperates the two widgets with equal width (=100)

Categories

Resources