pyqt5 show which button was clicked - python

I am new to PyQT5 and I want to have several buttons and have the one clicked last in a "checked" state. When another button is clicked the previous one gets "unchecked" while the clicked one gets "checked".
import sys
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

Building off of your code, you can add button1 and button2 to a QButtonGroup with the exclusive property set to True.
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.btn_grp = QButtonGroup()
self.btn_grp.setExclusive(True)
self.btn_grp.addButton(self.button1)
self.btn_grp.addButton(self.button2)
self.btn_grp.buttonClicked.connect(self.on_click)
self.show()
def on_click(self, btn):
pass # do something with the button clicked
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Here I've also connected an empty slot to the signal QButtonGroup.buttonClicked, which is emitted whenever a button from the group is clicked.
To find out which button is the currently checked button, you can invoke the methods QButtonGroup.checkedButton() and QButtonGroup.checkedId(). The former will return a QButton object and the latter will return an index int, corresponding to the order in which the buttons were added to the group.

You can use functools partial or the sender method to check which button was pressed:
import sys
from PyQt5.QtWidgets import *
from functools import partial
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button1.clicked.connect(partial(self.clicked_btn, 'Button 1'))
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.button2.clicked.connect(partial(self.clicked_btn, 'Button 2'))
self.show()
def clicked_btn(self, value):
print(f'{value} clicked')
sender = self.sender()
print(f'Sender says: {sender.text()} was clicked')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

Make the buttons checkable by setCheckable(True)
Add the buttons to a QButtonGroup() and the rest is sorted automatically:
class Example(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(30, 30, 400, 200)
self.initUI()
def initUI(self):
self.button1 = QPushButton(self)
self.button1.setGeometry(40, 40, 100, 50)
self.button1.setText("Button 1")
self.button1.setCheckable(True)
self.button2 = QPushButton(self)
self.button2.setGeometry(150, 40, 100, 50)
self.button2.setText("Button 2")
self.button2.setCheckable(True)
self.my_button_group = QButtonGroup()
self.my_button_group.addButton(self.button1)
self.my_button_group.addButton(self.button2)
self.show()

Related

Using QStackedWidget in PyQt5

I have QStackedWidget in ApplicationWindow class and buttons which are going to point to different QWidgets in MenuWindow. I need a help with writing a function which would change the CurrentWidget according to button clicked - e.g. login_button would change the CurrentWidget to LoginWindow.
When trying to do it myself I ran into recursion problems as I have just started with learning Python.
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class ApplicationWindow(QWidget):
def __init__(self):
super(ApplicationWindow, self).__init__()
# stack = Controller()
self.menu = MenuWindow()
self.login = LoginWindow()
self.setGeometry(0, 0, 800, 600)
self.setWindowTitle('Finance tracker')
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.green)
self.setPalette(p)
self.stack = QStackedWidget()
self.stack.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
self.stack.addWidget(self.menu)
self.stack.addWidget(self.login)
self.stack.setCurrentWidget(self.menu)
layout = QVBoxLayout()
layout.addWidget(self.stack)
layout.setAlignment(Qt.AlignCenter)
self.setLayout(layout)
class MenuWindow(QWidget):
def __init__(self):
super(MenuWindow, self).__init__()
self.setGeometry(0, 0, 250, 200)
box = QVBoxLayout()
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.red)
self.setPalette(p)
label = QLabel('Welcome to finance tracker')
label.setStyleSheet('font: 24pt')
box.addWidget(label, alignment=Qt.AlignCenter)
login_button = QPushButton('Login')
login_button.clicked.connect(qApp.exit)
new_button = QPushButton('Create a new account')
new_button.clicked.connect(qApp.exit)
exit_button = QPushButton('Exit')
exit_button.clicked.connect(qApp.exit)
for button in [login_button, new_button, exit_button]:
button.setStyleSheet('font: 14pt')
button.setFixedSize(200, 50)
box.addWidget(button, alignment=Qt.AlignCenter)
self.setLayout(box)
self.show()
class LoginWindow(QWidget):
def __init__(self):
super(LoginWindow, self).__init__()
self.setGeometry(0, 0, 10, 250)
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.blue)
self.setPalette(p)
label = QLabel('Welcome to finance tracker')
box = QVBoxLayout()
box.addWidget(label)
self.setLayout(box)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ApplicationWindow()
window.show()
sys.exit(app.exec())
Since you are using QPushButtons to switch pages I would add them to a QButtonGroup. This way you can connect the QButtonGroup.buttonClicked[int] signal to QStackedWidget.setCurrentIndex. Keep a pointer to the QButtonGroup in your MenuWindow.
class MenuWindow(QWidget):
def __init__(self):
...
login_button = QPushButton('Login')
new_button = QPushButton('Create a new account')
exit_button = QPushButton('Exit')
exit_button.clicked.connect(qApp.exit)
self.btn_group = QButtonGroup()
for i, button in enumerate([login_button, new_button, exit_button]):
button.setStyleSheet('font: 14pt')
button.setFixedSize(200, 50)
box.addWidget(button, alignment=Qt.AlignCenter)
self.btn_group.addButton(button)
self.btn_group.setId(button, i + 1)
...
And now you can connect the signal and slot in your ApplicationWindow.
class ApplicationWindow(QWidget):
def __init__(self):
...
self.menu.btn_group.buttonClicked[int].connect(self.stack.setCurrentIndex)

How to add in PQT5 a event to a label

My Probleme is i want to add to a label respectively text a event in my case the mousePressEvent.But it dont work under this text is some code from me that doesn´t work.
self.label2.mousePressEvent = self.credits
def credits(self, event):
print("credits")
Here i get the error AttributeError: 'Window' object has no attribute 'label2'
I also try this one:
label2.mousePressEvent.connect(self.credits)
def credits(self):
print("credits")
That doenst work too :( Any Ideas i am glad if anybody can help me :(
if you need the full code here:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
class Window(QWidget):
def __init__(self):
super().__init__()
self.initMe()
def initMe(self):
label1 = QtWidgets.QLabel(self)
label1.setText("Überschrift mit namen des text adventure")
label1.setStyleSheet("font-size: 18px;color: black;")
label1.setGeometry(50, 50, 400, 100)
label1.move(350,50)
label2 = QtWidgets.QLabel(self)
label2.setText("Spielen")
label2.setStyleSheet("font-size: 18px;color: black;")
label2.setGeometry(50, 50, 400, 100)
label2.move(450, 120)
self.label2.mousePressEvent = self.spielen
label3 = QtWidgets.QLabel(self)
label3.setText("Settings")
label3.setStyleSheet("font-size: 18px;color: black;")
label3.setGeometry(50, 50, 400, 100)
label3.move(450, 200)
self.label3.mousePressEvent = self.settings
label4 = QtWidgets.QLabel(self)
label4.setText("Credits")
label4.setStyleSheet("font-size: 18px;color: black;")
label4.setGeometry(50, 50, 400, 100)
label4.move(450, 280)
self.label4.mousePressEvent = self.credits
QToolTip.setFont(QFont("Arial", 10 ))
button = QPushButton("Spiel beenden", self)
button.setGeometry(50,50,150,50)
button.setFont(QFont("Arial", 12))
button.move(820, 420)
button.setToolTip("<b>Button lel</b>")
button.clicked.connect(QtCore.QCoreApplication.instance().quit)
button.clicked.connect(self.gedruekt)
button.setStyleSheet("background-color: white;")
self.setGeometry(50,50,1000,500)
self.setWindowTitle("Gui lalal einhorn")
self.setWindowIcon(QIcon("cookie.png"))
self.setAutoFillBackground(True)
self.setStyleSheet("background-color: lightblue;")
self.move(500, 250)
self.show()
def spielen(self, event):
print("spielen")
def settings(self, event):
print("settings")
def credits(self, event):
print("credits")
def gedruekt(self):
print("Er hats getan ;(")
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Window()
sys.exit(app.exec_())
else:
print("Gui not created, because script used at liabary")
The problem is that the variables are not members of the classes so it is not necessary to use the self instance, for this it changes for example:
self.label2.mousePressEvent = self.spielen
to:
label2.mousePressEvent = self.spielen
If you want to use connect, this is only for signals, for this we create a custom QLabel class like the following:
class Label(QLabel):
clicked = pyqtSignal()
def __init__(self, parent=None):
QLabel.__init__(self, parent=parent)
def mousePressEvent(self, event):
self.clicked.emit()
In this case you will be as follows:
class Label(QLabel):
clicked = pyqtSignal()
def __init__(self, parent=None):
QLabel.__init__(self, parent=parent)
def mousePressEvent(self, event):
self.clicked.emit()
class Window(QWidget):
def __init__(self):
super().__init__()
self.initMe()
def initMe(self):
label1 = QLabel(self)
label1.setText("Überschrift mit namen des text adventure")
label1.setStyleSheet("font-size: 18px;color: black;")
label1.setGeometry(50, 50, 400, 100)
label1.move(350,50)
label2 = Label(self)
label2.setText("Spielen")
label2.setStyleSheet("font-size: 18px;color: black;")
label2.setGeometry(50, 50, 400, 100)
label2.move(450, 120)
label2.clicked.connect(self.spielen)
label3 = Label(self)
label3.setText("Settings")
label3.setStyleSheet("font-size: 18px;color: black;")
label3.setGeometry(50, 50, 400, 100)
label3.move(450, 200)
label3.clicked.connect(self.settings)
label4 = Label(self)
label4.setText("Credits")
label4.setStyleSheet("font-size: 18px;color: black;")
label4.setGeometry(50, 50, 400, 100)
label4.move(450, 280)
label4.clicked.connect(self.credits)
QToolTip.setFont(QFont("Arial", 10 ))
button = QPushButton("Spiel beenden", self)
button.setGeometry(50,50,150,50)
button.setFont(QFont("Arial", 12))
button.move(820, 420)
button.setToolTip("<b>Button lel</b>")
button.clicked.connect(self.close)
button.clicked.connect(self.gedruekt)
button.setStyleSheet("background-color: white;")
self.setGeometry(50,50,1000,500)
self.setWindowTitle("Gui lalal einhorn")
self.setWindowIcon(QIcon("cookie.png"))
self.setAutoFillBackground(True)
self.setStyleSheet("background-color: lightblue;")
self.move(500, 250)
self.show()
def spielen(self):
print("spielen")
def settings(self):
print("settings")
def credits(self):
print("credits")
def gedruekt(self):
print("Er hats getan ;(")
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Window()
sys.exit(app.exec_())

PySide/PyQt Overlay widget

I am trying to achieve something like this in PySide: https://codepen.io/imprakash/pen/GgNMXO
What I want to do is create a child window frameless with a black overlay below.
I didn't succeed to create a child window frameless and the overlay...
This is a base code to replicate the HTML:
from PySide import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
popup = QtGui.QDialog(self)
popup.setWindowFlags(QtCore.Qt.FramelessWindowHint)
popup.setLayout(QtGui.QHBoxLayout())
popup.layout().addWidget(QtGui.QLabel("HI"))
popup.show()
print "clicked"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
If you comment the line with the FramelessWindowHint, the window comes, else nothing happen...
I really hope that someone could help me. Thank you for the time you spent to read my question.
I'll be using PyQt5 for this explanation. It might have some differences to PySide (which I'm not sure if its still maintained) and PyQt4, but it shouldn't be too hard to convert.
The following example has a parent widget which a few buttons. One of them (the obvious one) calls for the popup. I've prepared the example to deal with the parent resize but have not made any code regarding mouse events of dragging the popup (see mouseMoveEvent and mouseReleaseEvent for that).
So here is the code:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class TranslucentWidgetSignals(QtCore.QObject):
# SIGNALS
CLOSE = QtCore.pyqtSignal()
class TranslucentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TranslucentWidget, self).__init__(parent)
# make the window frameless
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.fillColor = QtGui.QColor(30, 30, 30, 120)
self.penColor = QtGui.QColor("#333333")
self.popup_fillColor = QtGui.QColor(240, 240, 240, 255)
self.popup_penColor = QtGui.QColor(200, 200, 200, 255)
self.close_btn = QtWidgets.QPushButton(self)
self.close_btn.setText("x")
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
self.close_btn.setFont(font)
self.close_btn.setStyleSheet("background-color: rgb(0, 0, 0, 0)")
self.close_btn.setFixedSize(30, 30)
self.close_btn.clicked.connect(self._onclose)
self.SIGNALS = TranslucentWidgetSignals()
def resizeEvent(self, event):
s = self.size()
popup_width = 300
popup_height = 120
ow = int(s.width() / 2 - popup_width / 2)
oh = int(s.height() / 2 - popup_height / 2)
self.close_btn.move(ow + 265, oh + 5)
def paintEvent(self, event):
# This method is, in practice, drawing the contents of
# your window.
# get current window size
s = self.size()
qp = QtGui.QPainter()
qp.begin(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
qp.setPen(self.penColor)
qp.setBrush(self.fillColor)
qp.drawRect(0, 0, s.width(), s.height())
# drawpopup
qp.setPen(self.popup_penColor)
qp.setBrush(self.popup_fillColor)
popup_width = 300
popup_height = 120
ow = int(s.width()/2-popup_width/2)
oh = int(s.height()/2-popup_height/2)
qp.drawRoundedRect(ow, oh, popup_width, popup_height, 5, 5)
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
qp.setFont(font)
qp.setPen(QtGui.QColor(70, 70, 70))
tolw, tolh = 80, -5
qp.drawText(ow + int(popup_width/2) - tolw, oh + int(popup_height/2) - tolh, "Yep, I'm a pop up.")
qp.end()
def _onclose(self):
print("Close")
self.SIGNALS.CLOSE.emit()
class ParentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ParentWidget, self).__init__(parent)
self._popup = QtWidgets.QPushButton("Gimme Popup!!!")
self._popup.setFixedSize(150, 40)
self._popup.clicked.connect(self._onpopup)
self._other1 = QtWidgets.QPushButton("A button")
self._other2 = QtWidgets.QPushButton("A button")
self._other3 = QtWidgets.QPushButton("A button")
self._other4 = QtWidgets.QPushButton("A button")
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(self._popup)
hbox.addWidget(self._other1)
hbox.addWidget(self._other2)
hbox.addWidget(self._other3)
hbox.addWidget(self._other4)
self.setLayout(hbox)
self._popframe = None
self._popflag = False
def resizeEvent(self, event):
if self._popflag:
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
def _onpopup(self):
self._popframe = TranslucentWidget(self)
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
self._popframe.SIGNALS.CLOSE.connect(self._closepopup)
self._popflag = True
self._popframe.show()
def _closepopup(self):
self._popframe.close()
self._popflag = False
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
main = ParentWidget()
main.resize(500, 500)
main.show()
sys.exit(app.exec_())
Which results in the following:
The logic is the following. You create an empty Widget and manually draw the background and popup (paintEvent). You add a button for closing the popup. For this you build a Signal and let the parent widget do the closing. This is important because you need to make the parent widget control some important elements of the popup (such as closing, resizng, etc.). You can add far more complexity but hopefully the example will suffice for starters.
Thanks to armatita, I succeed to get what I wanted. For now, there are some issues but it works and I get the result that I wanted.
I give you the code to the next who will be looking for the same thing.
from PySide import QtCore, QtGui
import sys
class CtmWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.button = QtGui.QPushButton("Close Overlay")
self.setLayout(QtGui.QHBoxLayout())
self.layout().addWidget(self.button)
self.button.clicked.connect(self.hideOverlay)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
path = QtGui.QPainterPath()
path.addRoundedRect(QtCore.QRectF(self.rect()), 10, 10)
mask = QtGui.QRegion(path.toFillPolygon().toPolygon())
pen = QtGui.QPen(QtCore.Qt.white, 1)
painter.setPen(pen)
painter.fillPath(path, QtCore.Qt.white)
painter.drawPath(path)
painter.end()
def hideOverlay(self):
self.parent().hide()
class Overlay(QtGui.QWidget):
def __init__(self, parent, widget):
QtGui.QWidget.__init__(self, parent)
palette = QtGui.QPalette(self.palette())
palette.setColor(palette.Background, QtCore.Qt.transparent)
self.setPalette(palette)
self.widget = widget
self.widget.setParent(self)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor(0, 0, 0, 127)))
painter.end()
def resizeEvent(self, event):
position_x = (self.frameGeometry().width()-self.widget.frameGeometry().width())/2
position_y = (self.frameGeometry().height()-self.widget.frameGeometry().height())/2
self.widget.move(position_x, position_y)
event.accept()
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
self.popup = Overlay(self, CtmWidget())
self.popup.hide()
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
self.popup.show()
print "clicked"
def resizeEvent(self, event):
self.popup.resize(event.size())
event.accept()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Once again thank you both of you(ymmx and armatita) to spend time on my issue.
did you try replacing popup.show() by popup.exec_()? and remove self as a parameter of the Qdialog? I change QDialog to QmessageBox to be able to quit the subwindow but it still work with the QDialog.
popup = QMessageBox()
popup.setWindowFlags( Qt.FramelessWindowHint)
popup.setLayout( QHBoxLayout())
popup.layout().addWidget( QLabel("HI"))
popup.exec_()
update
class Popup(QDialog ):
def __init__(self):
super().__init__()
self.setWindowFlags( Qt.CustomizeWindowHint)
self.setLayout( QHBoxLayout())
Button_close = QPushButton('close')
self.layout().addWidget( QLabel("HI"))
self.layout().addWidget( Button_close)
Button_close.clicked.connect( self.close )
self.exec_()
print("clicked")
def mousePressEvent(self, event):
self.oldPos = event.globalPos()
def mouseMoveEvent(self, event):
delta = QPoint (event.globalPos() - self.oldPos)
#print(delta)
self.move(self.x() + delta.x(), self.y() + delta.y())
self.oldPos = event.globalPos()
class MainWindow( QWidget):
def __init__(self):
QWidget.__init__(self)
self.resize(800, 500)
self.button = QPushButton("Click Me")
self.setLayout( QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
Popup( )
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

Python PyQt4 change image pressing button

I am trying to generate a visualizer where each time you press a button the image in a window change. The image have to be in the same window where the button is and it has to replace the previous image.
So for I am able to show the button and the first image. But I cannot connect the click button with the image updating process.
This is my code so far:
author__ = 'lpp'
#!/usr/bin/python
import os,sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
QtGui.QToolTip.setFont(QtGui.QFont('Test', 10))
self.setToolTip('This is a <b>QWidget</b> widget')
# Show image
pic = QtGui.QLabel(self)
pic.setGeometry(10, 10, 800, 800)
pic.setPixmap(QtGui.QPixmap( "/home/lpp/Desktop/Image1.png"))
# Show button
btn = QtGui.QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.resize(btn.sizeHint())
btn.clicked.connect(self.fun)
btn.move(50, 50)
self.setGeometry(300, 300, 2000, 1500)
self.setWindowTitle('Tooltips')
self.show()
# Connect button to image updating
def fun(self):
#print("Test!!!")
pic = QtGui.QLabel(self)
pic.setGeometry(100, 10, 800, 800)
pic.setPixmap(QtGui.QPixmap( "/home/lpp/Desktop/image2.png"))
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
All but the "def fun" works.
I also tried these functions but it did not work:
def fun(self):
pic = QtGui.QLabel(self)
pic.setGeometry(100, 10, 800, 800)
pic.setPixmap(QtGui.QPixmap( "/home/lpp/Desktop/image2.png"))
return (pic)
def fun(self):
#print("Test!!!")
pic = QtGui.QLabel(self)
pic.setGeometry(100, 10, 800, 800)
pic.setPixmap(QtGui.QPixmap( "/home/lpp/Desktop/image2.png"))
return self.show()
If you want the previous image you should not create a new QLabel, but just update the QPixmap.
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
QtGui.QToolTip.setFont(QtGui.QFont('Test', 10))
self.setToolTip('This is a <b>QWidget</b> widget')
# Show image
self.pic = QtGui.QLabel(self)
self.pic.setGeometry(10, 10, 800, 800)
self.pic.setPixmap(QtGui.QPixmap("/home/lpp/Desktop/image1.png"))
# Show button
btn = QtGui.QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.resize(btn.sizeHint())
btn.clicked.connect(self.fun)
btn.move(50, 50)
self.setGeometry(300, 300, 2000, 1500)
self.setWindowTitle('Tooltips')
self.show()
# Connect button to image updating
def fun(self):
self.pic.setPixmap(QtGui.QPixmap( "/home/lpp/Desktop/image2.png"))
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Creating a button for PyQT window at each loop

class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
self.initUI()
def initUI(self):
YDrive = QtGui.QAction(QtGui.QIcon('y.gif'), 'Exit', self)
SDrive = QtGui.QAction('S', self)
GDrive = QtGui.QAction('G', self)
AddDrive = QtGui.QAction('+', self)
YDrive.triggered.connect(self.setYDir)
SDrive.triggered.connect(self.setSDir)
GDrive.triggered.connect(self.setGDir)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(YDrive)
self.toolbar.addAction(SDrive)
self.toolbar.addAction(GDrive)
self.toolbar.addAction(AddDrive)
#btn1 = QtGui.QPushButton("Button 1", self)
#btn1.move(30, 50)
#btn2 = QtGui.QPushButton("Button 2", self)
#btn2.move(150, 50)
#btn1.clicked.connect(self.buttonClicked)
#btn2.clicked.connect(self.buttonClicked)
self.setGeometry(300, 300, 250, 150)
self.center()
self.setWindowTitle('Message box')
self.show()
def setYDir(self):
myInputs[1] = "Y"
print "myInputs[1] CHANGED to Y"
myWorkDrive = "Y:\\HoC_Jobs\\"
shows = self.listDirs(myWorkDrive)
for elements in shows:
btn1 = QtGui.QPushButton(elements, self)
btn1.move(30, 50)
btn1.clicked.connect(self.buttonClicked)
What I'm trying to do in the last loop in setYDir is create a button for each element in the list shows. However, it doesn't seem to be working right. It does not update the buttons depending on thebutton I click in the toolbar. Any help?
Well, if you add components to a parent widget without using a layout and after you've called show on the parent, you'll have to show the children yourself.
Also, all your buttons are overlapping, so you'll only see the last one added. When posting source it's always good to strip it down to the minimum required to run it. In this case that would look something like this:
from PyQt4 import QtGui
import os
class Test(QtGui.QMainWindow):
def __init__(self):
super(Test, self).__init__()
self.initUI()
def initUI(self):
YDrive = QtGui.QAction("Y", self)
YDrive.triggered.connect(self.setYDir)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(YDrive)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Message box')
self.show()
def buttonClicked(self):
print "clicked"
def setYDir(self):
myWorkDrive = "/tmp"
shows = os.listdir(myWorkDrive)
i = 0
for elements in shows:
btn1 = QtGui.QPushButton(elements, self)
btn1.move(30, 50 + i)
i += 30
btn1.clicked.connect(self.buttonClicked)
btn1.show()
self.resize(self.width(), 50 + i)
if __name__ == '__main__':
app = QtGui.QApplication([])
t = Test()
t.show()
app.exec_()

Categories

Resources