How to remove black space when deleting widgets in PyQt5 - python

I have a code to generate a GUI with PyQt5 that enables a user to create multiple buttons (QPushButton) based on an entry (QLineEdit), and to delete these buttons when pressing an "X" button (deleteLater()).
My problem is that when deleting some of these buttons by pressing the associated X-button, this leaves a small empty space where the buttons were initially, and I therefore wonder how to remove these spaces?
Image of the empty spaces
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QGroupBox, QScrollArea, QLabel
from PyQt5.QtCore import Qt
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setWindowTitle("My Program")
self.setGeometry(100, 100, 1500, 1500)
self.initUI()
def initUI(self):
widgets = MainWidgets()
self.setCentralWidget(widgets)
class MainWidgets(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.grid = QGridLayout()
self.grid.setColumnStretch(0, 1)
self.grid.setColumnStretch(1, 1)
self.grid.setColumnStretch(2, 1)
self.grid.setColumnStretch(3, 1)
self.grid.setColumnStretch(4, 1)
self.groupBox = QGroupBox("Labels")
self.groupBox.setStyleSheet('''
QGroupBox::title {
subcontrol-position: top center;
}
''')
right_column_layout = QVBoxLayout(self.groupBox)
scrollArea = QScrollArea()
scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
scrollArea.setWidgetResizable(True)
right_column_layout.addWidget(scrollArea)
scrollArea.setWidget(RightColWidgets())
self.grid.addWidget(self.groupBox, 0, 5, 1, 5)
self.setLayout(self.grid)
class RightColWidgets(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.layout = QVBoxLayout(self)
self.labelEntry = QLineEdit(self)
self.addLabelButton = QPushButton(self)
self.addLabelButton.setText("Add Label")
self.addLabelButton.clicked.connect(self.addNewLabel)
self.emptyspace = QLabel(self)
self.layout.addWidget(self.labelEntry, stretch=0)
self.layout.addWidget(self.addLabelButton, stretch=0)
self.layout.addWidget(self.emptyspace, stretch=1)
def addNewLabel(self):
labelname = self.labelEntry.text()
newLabelItems = Labels(self, labelname)
self.layout.insertWidget(2, newLabelItems)
class Labels(QWidget):
def __init__(self, parent, labelname, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.mylabelname = labelname
self.initUI()
def initUI(self):
self.labelButton = QPushButton(self)
self.labelButton.setText(str(self.mylabelname))
self.labelButton.setStyleSheet("""
QPushButton {border: 1px solid back; background: rgba(103, 186, 181, 0.5); padding-top: 10px; padding-bottom: 10px}
""")
self.labelButton.clicked.connect(self.printbutton)
self.buttonErase = QPushButton(self)
self.buttonErase.setText("X")
self.buttonErase.setStyleSheet("""
QPushButton {border: 1px solid back; padding-right: 5 px; padding-left: 5 px; padding-top: 10px; padding-bottom: 10px}
""")
self.buttonErase.clicked.connect(self.erasebutton)
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.labelButton, stretch=1)
layout.addWidget(self.buttonErase, stretch=0)
def printbutton(self):
print('clicked:', self.labelButton.text())
def erasebutton(self):
self.labelButton.deleteLater()
self.buttonErase.deleteLater()
if __name__ == '__main__':
app = QApplication(sys.argv)
# app.setStyle('Fusion')
window = MyWindow()
window.showMaximized()
sys.exit(app.exec_())

Deleting the children does not delete the container, so what you see is the empty Labels widget with the spacing of its layout contentsMargins().
A simple solution could be to directly connect the button with its own deleteLeter(), which automatically deletes its children:
self.buttonErase.clicked.connect(self.deleteLater)
A better solution would be to connect the signal to the parent and let it do everything necessary in a cleaner way, as you might need to keep track of the existing widgets (for instance, to remove them from the list of currently existing labels):
class RightColWidgets(QWidget):
# ...
def addNewLabel(self):
labelname = self.labelEntry.text()
newLabelItems = Labels(self, labelname)
self.layout.insertWidget(2, newLabelItems)
newLabelItems.buttonErase.clicked.connect(
lambda: self.deleteLabel(newLabelItems))
def deleteLabel(self, widget):
self.layout.removeWidget(widget)
widget.deleteLater()
Obviously, in this case you don't need to connect the clicked signal in the initUi of the Label class anymore.
Note that layout() is an existing (and dynamic) property of any QWidget, so you should not overwrite it.

Related

How do I modify spacing in nested PyQt layouts?

Currently, I have a nested QVBoxLayout in the first column of a QHBoxLayout, but no matter my changes to .setContentMargins or .setSpacing nothing changes in that first column.
import sys
import io
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView
class MyApp(QWidget):
def __init__(self):
super().__init__()
# Main widget/window
self.setWindowTitle('Test')
self.window_width, self.window_height = 1600, 900
self.setMinimumSize(self.window_width, self.window_height)
layout = QHBoxLayout()
self.setLayout(layout)
leftside = QWidget()
leftlayout = QVBoxLayout()
# Creating textbox and adding to leftside GUI
lineEdit = QLineEdit()
leftlayout.addWidget(lineEdit)
leftlayout.addWidget(QPushButton('Placeholder'))
leftside.setLayout(leftlayout)
# Adding both widgets to main layout
testWidget = QWidget()
testWidget.setStyleSheet("background-color: blue")
layout.addWidget(leftside, 2)
layout.addWidget(testWidget, 8)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyleSheet('''
QWidget {
font-size: 20px;
}
''')
myApp = MyApp()
myApp.show()
try:
sys.exit(app.exec_())
except SystemExit:
print('Closing Window...')
Leaves me with this result:
What I want:
Use addStretch() method:
class MyApp(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Test")
self.window_width, self.window_height = 1600, 900
self.setMinimumSize(self.window_width, self.window_height)
leftside = QWidget()
leftlayout = QVBoxLayout(leftside)
lineEdit = QLineEdit()
leftlayout.addWidget(lineEdit)
leftlayout.addWidget(QPushButton("Placeholder"))
leftlayout.addStretch()
testWidget = QWidget()
testWidget.setStyleSheet("background-color: blue")
layout = QHBoxLayout(self)
layout.addWidget(leftside)
layout.addWidget(testWidget, stretch=1)

How to make QLabel subwidgets inside a QScrollArea use wordwrap instead of expanding the container widget?

My code has two files. One is the "main" file that uses a fixed size QFrame instead of the standard window frame. The second is also a subclassed QWidget for adding to the QScrollArea in the main widget.
I want the QFrame of the subwidget to be fixed and the label to actually use the wordwrap property instead of just making it longer to fit and screwing up the whole QScrollArea scrolling area. I have tried using QSizePolicy for the container_widget and QFrame of the subwidget. A minimal reproducible example is as follows.
main_window.py
import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
from subwidget import SubWidget
class Window(qtw.QWidget):
def __init__(self):
super().__init__()
# Configure Window
self.setWindowFlags(qtc.Qt.FramelessWindowHint)
self.setAttribute(qtc.Qt.WA_TranslucentBackground)
self.setFixedSize(350, 450)
# Init Methods
self.setupUI()
self.refresh_entries()
self.show()
def setupUI(self):
# Main Layout/Frame
self.main_layout = qtw.QHBoxLayout()
self.main_frame = qtw.QFrame()
self.main_frame_layout = qtw.QVBoxLayout()
# Set Layouts
self.setLayout(self.main_layout)
self.main_layout.addWidget(self.main_frame)
self.main_frame.setLayout(self.main_frame_layout)
# Configure QFrame
self.main_frame.setContentsMargins(10, 10, 10, 10)
self.main_frame.setObjectName("main_frame")
self.main_frame.setStyleSheet("""
border: None;
border-radius: 10px;
background: #1E1E1E;
""")
# Secondary Layout/Widget
self.main_scroll_area = qtw.QScrollArea()
self.container_widget = qtw.QWidget()
self.container_layout = qtw.QVBoxLayout()
self.main_scroll_area.setObjectName("main_scroll_area")
self.main_scroll_area.setWidgetResizable(True)
self.main_scroll_area.setVerticalScrollBarPolicy(qtc.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.main_scroll_area.setHorizontalScrollBarPolicy(qtc.Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.main_scroll_area.setWidget(self.container_widget)
self.container_widget.setLayout(self.container_layout)
self.container_widget.setObjectName("container_widget")
# Widget -> Layout
self.main_frame_layout.addWidget(self.main_scroll_area, 0, qtc.Qt.AlignmentFlag.AlignHCenter | qtc.Qt.AlignmentFlag.AlignCenter)
def refresh_entries(self):
self.clear_entries()
for i in range(5):
self.container_layout.addWidget(SubWidget(i ** i ** i, i))
def clear_entries(self):
for i in reversed(range(self.container_layout.count())):
try:
widget = self.container_layout.itemAt(i).widget()
widget.setParent(None)
except Exception:
pass
if __name__ == "__main__":
app = qtw.QApplication(sys.argv)
win = Window()
sys.exit(app.exec())
and subwidget.py
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
class SubWidget(qtw.QWidget):
def __init__(self, name, index):
super().__init__()
# Variables
self.name = str(name)
self.index = index
# Init Methods
self.setupUI()
self.show()
def setupUI(self):
# Main Layout/Frame
self.main_layout = qtw.QHBoxLayout()
self.main_frame = qtw.QFrame()
self.main_frame_layout = qtw.QVBoxLayout()
# Set Layouts
self.setLayout(self.main_layout)
self.main_layout.addWidget(self.main_frame)
self.main_frame.setLayout(self.main_frame_layout)
# Configure QFrame
self.main_frame.setContentsMargins(5, 5, 5, 5)
self.main_frame.setStyleSheet("""
border: None;
border-radius: 5px;
background: #000000;
""")
# Secondary Layout/Widget
self.name_lbl = qtw.QLabel()
# Configure Seondary Widgets
self.name_lbl.setText(self.name)
self.name_lbl.setStyleSheet("""
color: #FFFFFF;
""")
self.name_lbl.setWordWrap(True) # https://stackoverflow.com/questions/49838817/how-to-resize-qlabels-to-fit-contents-in-qscrollarea
# Widget -> Layout
self.main_frame_layout.addWidget(self.name_lbl, 0, qtc.Qt.AlignmentFlag.AlignHCenter | qtc.Qt.AlignmentFlag.AlignCenter)
This is a visual of the resulting window/frame.
A Wrapable Anywhere QLabel
My way to achieve this to subclass QLabel and and implement the paintEvent, where you can set the text alignment to TextWrapAnywhere when you drawItemText.
Here is a sample code.
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QStyleOption, QVBoxLayout, QWidget, QStyle
class SuperQLabel(QLabel):
def __init__(self, *args, **kwargs):
super(SuperQLabel, self).__init__(*args, **kwargs)
self.textalignment = Qt.AlignLeft | Qt.TextWrapAnywhere
self.isTextLabel = True
self.align = None
def paintEvent(self, event):
opt = QStyleOption()
opt.initFrom(self)
painter = QPainter(self)
self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)
self.style().drawItemText(painter, self.rect(),
self.textalignment, self.palette(), True, self.text())
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setFixedSize(100, 200)
self.label = QLabel()
self.label.setWordWrap(True)
self.label.setText("1111111111111111111111111111")
self.slabel = SuperQLabel()
self.slabel.setText("111111111111111111111111111")
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.mainlayout = QVBoxLayout()
self.mainlayout.addWidget(self.label)
self.mainlayout.addWidget(self.slabel)
self.centralwidget.setLayout(self.mainlayout)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The result.
Note: this work is tested with pyqt5, pyside2, pyside6 and should work in qt5 as well (in c++).

How to bring QLineEdit() & QPushButton to centre of Login window?

I am creating a LoginWindow and am using QLineEdit in order to make a place for my users to enter their details. Right now, I'm focused on creating the GUI. As shown in the picture, I am not sure why the layout looks like that, considering how I have setAlignment to AlignCenter. This also goes for QPushButton. Is there a class I am not aware to fix this formatting issue?
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QLineEdit, QVBoxLayout
import time #For time sleep
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("MidiScribe - Login Window")
self.setFixedSize(800,800)
self.setStyleSheet("""background-color: crimson;
border-color: maroon;
border: 2.5px outset rgb(128, 128, 128);
border-radius: 3px;""")
container = QWidget()
self.setCentralWidget(container)
mainLayout = QVBoxLayout(container)
self.username = QLineEdit()
self.username.setFixedWidth(300)
self.username.setStyleSheet("""background-color: white;""")
mainLayout.addWidget(self.username)
self.username.setAlignment(QtCore.Qt.AlignCenter)
self.setLayout(mainLayout)
self.password = QLineEdit()
self.password.setFixedWidth(300)
self.password.setStyleSheet("""background-color: white""")
mainLayout.addWidget(self.password)
self.password.setAlignment(QtCore.Qt.AlignCenter)
self.setLayout(mainLayout)
self.loginbutton = QPushButton("Login")
self.loginbutton.setFixedSize(50,50)
self.loginbutton.setStyleSheet("QPushButton { background-color: lightcoral }"
"QPushButton:Hover { background-color: lightpink }"
"QPushButton:pressed { background-color: indianred }" )
mainLayout.addWidget(self.loginbutton)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
There are many solutions for this case, but among them is to use a container that has the minimum size to show all the widgets and that is established through a QGridLayout:
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("MidiScribe - Login Window")
self.setFixedSize(800, 800)
self.setStyleSheet(
"""background-color: crimson;
border-color: maroon;
border: 2.5px outset rgb(128, 128, 128);
border-radius: 3px;"""
)
self.username = QLineEdit(alignment=QtCore.Qt.AlignCenter)
self.username.setFixedWidth(300)
self.username.setStyleSheet("""background-color: white;""")
self.password = QLineEdit(alignment=QtCore.Qt.AlignCenter)
self.password.setFixedWidth(300)
self.password.setStyleSheet("""background-color: white""")
self.loginbutton = QPushButton("Login")
self.loginbutton.setFixedSize(50, 50)
self.loginbutton.setStyleSheet(
"QPushButton { background-color: lightcoral }"
"QPushButton:Hover { background-color: lightpink }"
"QPushButton:pressed { background-color: indianred }"
)
container = QWidget(objectName="container")
container.setStyleSheet("QWidget#container{border: none}")
container.setContentsMargins(0, 0, 0, 0)
lay = QVBoxLayout(container)
lay.addWidget(self.username, alignment=QtCore.Qt.AlignCenter)
lay.addWidget(self.password, alignment=QtCore.Qt.AlignCenter)
lay.addWidget(self.loginbutton, alignment=QtCore.Qt.AlignCenter)
container.setFixedSize(container.sizeHint())
central_widget = QWidget()
self.setCentralWidget(central_widget)
grid_layout = QGridLayout(central_widget)
grid_layout.addWidget(container, 1, 1)
Just do alignment for mainLayout:
mainLayout.addWidget(self.loginbutton, alignment=QtCore.Qt.AlignCenter)
mainLayout.setAlignment(QtCore.Qt.AlignCenter)

QScroller on QListWidget in QTabWidget is not work

In nutshell, I have QTabWidget which contain tab1 and tab2. Each of tab1 and tab2 contains a QListWidget. I would like to use QScroller on each of the QListWidget.
Here is the code (The simplest version).:
import sys
from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QAbstractItemView, QScrollerProperties, QScroller, QVBoxLayout, QListWidget,
QTabWidget, QApplication, QLabel, QListWidgetItem)
from PyQt5.QtCore import Qt
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.resize(700, 300)
mainLayout = QVBoxLayout()
self.tabWidget = QTabWidget()
self.tabWidget.setStyleSheet("QTabBar::tab { height: 50px; width: 250px; }")
mainLayout.addWidget(self.tabWidget)
myBoxLayout = QHBoxLayout()
self.tabWidget.setLayout(myBoxLayout)
self.tab1 = WidgetTab1()
self.tab2 = WidgetTab2()
self.tabWidget.addTab(self.tab1, 'Tab1')
self.tabWidget.addTab(self.tab2, 'Tab2')
self.setLayout(mainLayout)
class WidgetTab1(QWidget):
def __init__(self):
super().__init__()
self.hbox = QHBoxLayout()
# Create the list
self.mylist = QListWidget()
self.mylist.setStyleSheet("QListWidget::item { border-bottom: 1px solid gray; }")
self.mylist.setFocusPolicy(Qt.NoFocus)
self.mylist.setSelectionMode(QAbstractItemView.NoSelection)
self.mylist.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.mylist.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
for i in range(20):
item = QListWidgetItem(self.mylist)
self.mylist.addItem(item)
self.mylist.setItemWidget(item, QLabel(str(i)))
self.sp = QScrollerProperties()
self.sp.setScrollMetric(QScrollerProperties.DragVelocitySmoothingFactor, 0.6)
self.sp.setScrollMetric(QScrollerProperties.MinimumVelocity, 0.0)
self.sp.setScrollMetric(QScrollerProperties.MaximumVelocity, 0.2)
self.sp.setScrollMetric(QScrollerProperties.AcceleratingFlickMaximumTime, 0.1)
self.sp.setScrollMetric(QScrollerProperties.AcceleratingFlickSpeedupFactor, 1.2)
self.sp.setScrollMetric(QScrollerProperties.SnapPositionRatio, 0.2)
self.sp.setScrollMetric(QScrollerProperties.MaximumClickThroughVelocity, 1)
self.sp.setScrollMetric(QScrollerProperties.DragStartDistance, 0.001)
self.sp.setScrollMetric(QScrollerProperties.MousePressEventDelay, 0.5)
self.scroller = QScroller.scroller(self.mylist.viewport())
self.scroller.setScrollerProperties(self.sp)
self.scroller.grabGesture(self.mylist.viewport(), QScroller.LeftMouseButtonGesture)
self.mylist.show()
self.hbox.addWidget(self.mylist)
self.setLayout(self.hbox)
class WidgetTab2(QWidget):
def __init__(self):
super().__init__()
self.hbox = QHBoxLayout()
# Create the list
self.mylist = QListWidget()
self.mylist.setStyleSheet("QListWidget::item { border-bottom: 1px solid gray; }")
self.mylist.setFocusPolicy(Qt.NoFocus)
self.mylist.setSelectionMode(QAbstractItemView.NoSelection)
self.mylist.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.mylist.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
for i in range(19, 0, -1):
item = QListWidgetItem(self.mylist)
self.mylist.addItem(item)
self.mylist.setItemWidget(item, QLabel(str(i)))
self.sp = QScrollerProperties()
self.sp.setScrollMetric(QScrollerProperties.DragVelocitySmoothingFactor, 0.6)
self.sp.setScrollMetric(QScrollerProperties.MinimumVelocity, 0.0)
self.sp.setScrollMetric(QScrollerProperties.MaximumVelocity, 0.2)
self.sp.setScrollMetric(QScrollerProperties.AcceleratingFlickMaximumTime, 0.1)
self.sp.setScrollMetric(QScrollerProperties.AcceleratingFlickSpeedupFactor, 1.2)
self.sp.setScrollMetric(QScrollerProperties.SnapPositionRatio, 0.2)
self.sp.setScrollMetric(QScrollerProperties.MaximumClickThroughVelocity, 1)
self.sp.setScrollMetric(QScrollerProperties.DragStartDistance, 0.001)
self.sp.setScrollMetric(QScrollerProperties.MousePressEventDelay, 0.5)
self.scroller = QScroller.scroller(self.mylist.viewport())
self.scroller.setScrollerProperties(self.sp)
self.scroller.grabGesture(self.mylist.viewport(), QScroller.LeftMouseButtonGesture)
self.mylist.show()
self.hbox.addWidget(self.mylist)
self.setLayout(self.hbox)
if __name__ == '__main__':
qApplication = QApplication(sys.argv)
window = MainWindow()
window.show()
qApplication.exec_()
The problem is, the QScroller only work in the first tab. For example, If I choose tab1 at first and scroll on it. Then I switch to tab2, the scroll on tab2 will not work. If I choose tab2 first and scroll on it. Then I switch to tab1, the scroll on tab1 will not work.
I also have tried to ungrabGesture every I switch the tab, but it does not work.
Am I implement the QScroller in the wrong way?
Thanks #G.M. for your comment.
I solve the problem by upgrading the PyQt version from 5.11.3 to 5.13.0

PyQt: Modifying Widget Object from another Function

I am making Multi-Page application in PyQt4, so whenever user does specific action (clicking a button for example) there is an update in widgets.
For example, There are 5 widgets and one button:
3 widgets are hidden, 2 widgets are shown.
Whenever i click the button, it will hide 2 widgets, and show those 3.
So in code, it should be something like this:
# startup
def somefunc(self):
widget1 = QtGui.QLabel("Widget1", self)
widget2 = QtGui.QLabel("Widget2", self)
widget3 = QtGui.QLabel("Widget3", self)
widget4 = QtGui.QLabel("Widget4", self)
widget5 = QtGui.QLabel("Widget5", self)
widget1.setHidden()
widget2.setHidden()
widget3.setHidden()
widget4.show()
widget5.show()
btn = QtGui.QPushButton("Click", self)
btn.clicked.connect(self.SomeotherFunc)
# My Question: (Code down below doesn't work, it's for example)
def SomeotherFunc(self):
self.somefunc.widget1.Show()
self.somefunc.widget1.Show()
self.somefunc.widget1.Show()
self.somefunc.widget4.setHidden()
self.somefunc.widget5.setHidden()
Full Code:
import sys
from PyQt4 import QtGui, QtCore
import resources
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(0, 0, 1280, 800)
self.setWindowTitle("E.S Quiz")
self.home()
def home(self):
pic = QtGui.QLabel(self)
pic.setGeometry(0, 0, 1280, 800)
pic.setPixmap(QtGui.QPixmap(":/images/background.png"))
btn = QtGui.QPushButton("", self)
btn.resize(150, 120)
btn.move(600, 400)
btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
btn.setObjectName('btn')
btn.setStyleSheet("#btn {background-image: url(':/images/Button1.png'); border: none; }"
"#btn:hover { background-image: url(':/images/Button1Hover.png'); }"
"#btn:pressed { background-image: url(':/images/Button1Press.png'); }")
btn.clicked.connect(self.test)
self.show()
def test(self):
print "Here"
def startup():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
startup()
Question:
How do i modify some functions widgets from another function?
You need to store references to the subwidgets on the main window using self
def func(self):
self.btn = QPushButton(...)
...
def other_func(self):
self.btn.setText('Hello')
I've edited your code. I believe this will do the job. Just push the button, and see the label disappear. Have fun :-)
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(40, 80, 1280, 800)
# You should make a 'mainWidget' that
# serves as a container for all your other
# widgets.
self.mainWidget = QtGui.QWidget()
self.setCentralWidget(self.mainWidget)
self.setWindowTitle("E.S Quiz")
self.home()
self.show()
def home(self):
# Make the label
pic = QtGui.QLabel(parent = self.mainWidget)
pic.setText("My label")
pic.setGeometry(0, 0, 1280, 800)
#pic.setPixmap(QtGui.QPixmap(":/images/background.png"))
# Make a label that will disappear when
# you push the button.
self.myLabel = QtGui.QLabel(parent = self.mainWidget)
self.myLabel.setText("My removable label")
self.myLabel.setGeometry(40,40,200,100)
# Make the button
self.btn = QtGui.QPushButton(parent = self.mainWidget)
self.btn.setCheckable(True)
self.btn.setText("My button")
self.btn.resize(150, 120)
self.btn.move(600, 400)
self.btn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.btn.setObjectName('btn')
# self.btn.setStyleSheet("#btn {background-image: url(':/images/Button1.png'); border: none; }"
# "#btn:hover { background-image: url(':/images/Button1Hover.png'); }"
# "#btn:pressed { background-image: url(':/images/Button1Press.png'); }")
self.btn.clicked.connect(self.btnAction)
def btnAction(self, pressed):
print("Button pushed")
if(pressed):
self.myLabel.setVisible(False)
else:
self.myLabel.setVisible(True)
def startup():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
startup()

Categories