Creating a pop-up window from custom pushbutton python - python

I am trying to create a pop-up window that gets popped-up from pressing on a QPushButton. However, I have a separate QPushButton class that I would like to use. I can't seem to get it working. Anything I am doing wrong?
#import ... statements
import sys
# from ... import ... statements
from PyQt5.QtWidgets import (QMainWindow, QApplication, QPushButton, QGridLayout, QWidget, QHBoxLayout, QLabel,
QVBoxLayout)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QFontDatabase, QColor, QPalette, QMovie
from skimage import transform, io
# Create main window of the widget
class MainWindow(QWidget):
def __init__(self):
super().__init__()
#Set a title inside the widget
self.titleLabel = QLabel()
titleText = "some title text"
self.titleLabel.setText(titleText)
# Give the label some flair
self.titleLabel.setFixedWidth(1000)
self.titleLabel.setAlignment(Qt.AlignCenter)
QFontDatabase.addApplicationFont(link_to_custom_font)
font = QFont()
font.setFamily("custom_font_name")
font.setPixelSize(50)
self.titleLabel.setFont(font)
# Set first button - The "Yes" Button
self.btn1 = myButtonOne("Yes")
#Initialize GUI
self.layoutGUI()
self.initUI()
def initUI(self):
self.fromleft = 200
self.fromtop = 100
self.w = 1000
self.h = 500
self.setGeometry(self.fromleft, self.fromtop, self.w, self.h)
def layoutGUI(self):
hbox = QHBoxLayout()
hbox.setSpacing(20)
hbox.addWidget(self.btn1)
vbox = QVBoxLayout()
vbox.addWidget(self.titleLabel)
vbox.addLayout(hbox)
self.setLayout(vbox)
class myButtonOne(QPushButton):
def __init__(self, parent=None):
super(myButtonOne, self).__init__(parent)
# Set maximum border size
imSize = io.imread(imagePath)
imHeight = imSize.shape[1]
imWidth = imSize.shape[0]
# Set first button - The "Yes" Button
yesImage = someImagePath
self.setStyleSheet("background-image: url(" + yesImage + ");"
"background-repeat: none;"
"background-position: center;"
"border: none")
self.setFixedSize(imWidth, imHeight)
self.clicked.connect(self.buttonOnePushed)
def buttonOnePushed(self):
textView().show()
def enterEvent(self, event):
newImage = someOtherImagePath
self.setStyleSheet("background-image: url("+newImage+");"
"background-repeat: none;"
"background-position: center;"
"border: none")
def leaveEvent(self, event):
newImage = someImagePath
self.setStyleSheet("background-image: url("+newImage+");"
"background-repeat: none;"
"background-position: center;"
"border: none")
class textView(QWidget):
def __init(self):
textView.__init__()
theText = QLabel()
#define sizes
self.height = 550
self.width = 250
# Open QWidget
self.initUI()
# Set the text for the QLabel
someText = "Some Text for the label"
theText.setText(someText)
def initUI(self):
self.show()
# Start GUI
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
So, I am trying to keep the QPushButton classes separate, so that I can customize them. I would like to keep it like that, especially to keep it clean and readable.

First off - please read: How to create a Minimal, Complete, and Verifiable example. I had a lot of work minimizing your code, which wasted a good amount of my time.
Nonetheless, here is a minimal working code, with your own button class:
import sys
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QLabel, QVBoxLayout
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.titleLabel = QLabel( "some label text" )
self.btn1 = myButtonOne( "button text" )
hbox = QVBoxLayout() # one vertical box seemed enough
hbox.addWidget( self.titleLabel )
hbox.addWidget( self.btn1 )
self.setLayout( hbox )
class myButtonOne(QPushButton):
def __init__(self, text, parent=None):
super(myButtonOne, self).__init__(text, parent)
self.clicked.connect(self.buttonOnePushed)
# add your customizations here
def buttonOnePushed (self) :
self.t = textView()
self.t.show()
class textView(QWidget):
def __init__(self):
super(textView, self).__init__()
self.theText = QLabel('test', self )
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
What have you done wrong in your code?
using textView().show() creates a local version of you textView-class and show()'s it:
def buttonOnePushed(self):
textView().show()
But, show() means that the code continues, where the end of your code comes, which results in cleaning up the locals. End - it's just shown for a microsecond.
def buttonOnePushed (self) :
self.t = textView()
self.t.show()
The code above stores the var as instance-attribute of the button, which is not cleaned up.
Furthermore you misspelled the init in your textView-class:
"__init" should be __init__ - else it is not called when using the constructor:
class textView(QWidget):
def __init(self):
textView.__init__()
Finally, you wanted to called show() twice:
in your textView-init you call initUI() which is calling show()
you calling show manually with textView().show()
Hope this helps! I did not include your personal style adjustments for readability.

Related

PyQt5 - Custom widgets open in separate windows rather than in same window

I'm new at PyQt, and I'm trying to create a main window containing two custom widgets, the first being a data grapher, the second being a QGridLayout containing QLabels. Problem is: the two widgets open in separate windows and have no content.
I've found multiple posts with a similar problem:
PyQt5 Custom Widget Opens in Another Window
Custom widget does not appear on Main Window
PyQt5 Custom Widget Opens in Another Window
And even a FAQ on this specific problem: https://www.pythonguis.com/faq/pyqt-widgets-appearing-as-separate-windows/
But I haven't been able to figure out why my code doesn't work. My aim is to obtain a result as shown below on the left, but instead I'm getting a result as shown on the right:
My code is the following (can be copied and run as it is):
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget, QGridLayout
from PyQt5.QtGui import QFont
import sys
import pyqtgraph as pg
class CustomWidget_1(QWidget):
def __init__(self):
super(CustomWidget_1, self).__init__()
self.channels = [1, 2, 3, 4, 5, 6, 7, 8]
self.win = pg.GraphicsLayoutWidget(title='Plot', size=(800, 600))
self.plots = list()
self.curves = list()
for i in range(len(self.channels)):
p = self.win.addPlot(row=i, col=0)
p.showAxis('left', False)
p.setMenuEnabled('left', False)
p.showAxis('bottom', False)
p.setMenuEnabled('bottom', False)
self.plots.append(p)
curve = p.plot()
self.curves.append(curve)
self.win.show()
print('CustomWidget_1 initialized.')
class CustomWidget_2(QWidget):
def __init__(self, labelnames):
super(CustomWidget_2, self).__init__()
self.grid = QGridLayout()
self.labelnames = labelnames
self.qlabels = []
for label in self.labelnames:
labelBox = QLabel(label)
labelBox.setFont(QFont('Arial', 16))
labelBox.setStyleSheet('border: 2px solid black;')
labelBox.setAlignment(Qt.AlignCenter)
self.qlabels.append(labelBox)
index = self.labelnames.index(label)
q, r = divmod(index, 6)
self.grid.addWidget(labelBox, q, r)
print('CustomWidget_2 initialized.')
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.labelnames = ['label 1', 'label 2', 'label 3']
self.CustomWidget_1 = CustomWidget_1()
self.CustomWidget_1.setParent(self)
self.CustomWidget_1.show()
self.CustomWidget_2 = CustomWidget_2(self.labelnames)
self.CustomWidget_2.setParent(self)
self.CustomWidget_2.show()
self.mainLayout = QVBoxLayout()
self.mainLayout.addWidget(self.CustomWidget_1)
self.mainLayout.addWidget(self.CustomWidget_2)
self.setLayout(self.mainLayout)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
predictVisualizer = MainWindow()
sys.exit(app.exec())
Could anyone tell me what I'm doing wrong and how I could fix it? Any pointers towards tutorials and/or templates would be greatly appreciated as well! Thanks!
you should write fewer lines of code and debug slowly, if you are new to pyqt5 you should read carefully the basic Layout creation, like you are creating a website interface, link: https://www.pythonguis.com/tutorials/pyqt-layouts/
This is the code I have edited, you can can refer:
import sys
from PyQt5.QtCore import QSize,Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget,QGridLayout,QVBoxLayout,QLabel,QHBoxLayout
from PyQt5.QtGui import QPalette, QColor
class CustomWidget_1(QWidget):
def __init__(self,color):
super(CustomWidget_1, self).__init__()
self.setAutoFillBackground(True)
layout = QGridLayout()
self.setLayout(layout)
self.setFixedSize(QSize(400,300))
palette = self.palette()
palette.setColor(QPalette.Window, QColor(color))
self.setPalette(palette)
class CustomWidget_2(QWidget):
def __init__(self,color):
super(CustomWidget_2, self).__init__()
self.setAutoFillBackground(True)
layout = QHBoxLayout()
self.setLayout(layout)
self.setFixedSize(QSize(400,134))
layout.setContentsMargins(70,0,0,0)
palette = self.palette()
palette.setColor(QPalette.Window, QColor(color))
self.setPalette(palette)
Label1 = QLabel()
Label1.setText('abc')
Label2 = QLabel()
Label2.setText('sad')
Label3 = QLabel()
Label3.setText('qv')
layout.addWidget(Label1)
layout.addWidget(Label2)
layout.addWidget(Label3)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("My App")
layout = QVBoxLayout()
layout.addWidget(CustomWidget_1("blue"))
layout.addWidget(CustomWidget_2("red"))
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

Adding or removing a QWidget without affecting any other widgets

I have a PyQT application with a toolbar, a set of buttons, and a bottom row of additional buttons. I'd like to add a TextEdit underneath the bottom row that the user can hide or show. I would like the TextEdit to extend the bottom portion when being shown but, when the user hides it, I would like that bottom portion removed without affecting the height, width, or sizing of any other of the buttons. Imagine just taking a pair of scissors to the TextEdit section when the user hides it but then gluing it back on when the user wants it back. Is this even possible to do in PyQt? The closest I've found is the implementation below which resizes all the buttons.
from PyQt5.QtCore import Qt, QPoint, QTimer, QThread, QSize
from PyQt5.QtGui import QFont, QImage, QPainter, QPen, QPixmap
from PyQt5.QtWidgets import (
QAction, QApplication, QCheckBox, QFileDialog, QHBoxLayout, QLabel,
QMainWindow, QMenu, QMenuBar, QPlainTextEdit, QPushButton, QSpacerItem,
QSizePolicy, QFrame,
QTextEdit, QVBoxLayout, QWidget, QGridLayout, QToolButton, QComboBox
)
from PyQt5.QtWidgets import QApplication
import sys
class AppWindow(QMainWindow):
def __init__(self, main_widget):
super(AppWindow, self).__init__()
self.main_widget = main_widget
self.setCentralWidget(self.main_widget)
class AppWidget(QWidget):
def __init__(self, panels=[]):
super(AppWidget, self).__init__()
self.panels = panels
self.main_layout = QVBoxLayout(self)
self.setSizePolicy(
QSizePolicy.MinimumExpanding,
QSizePolicy.MinimumExpanding
)
self.toolbar_frame = QFrame(self)
self.toolbar_frame_layout = QHBoxLayout(self.toolbar_frame)
self.toolbar_frame_layout.addStretch()
self.log_button = QToolButton(self.toolbar_frame)
self.log_button.setText('Toggle Log')
self.toolbar_frame_layout.addWidget(self.log_button)
self.toolbar_frame.setLayout(self.toolbar_frame_layout)
self.project_frame = QFrame(self)
self.project_frame_layout = QHBoxLayout(self.project_frame)
self.project_dropdown = QComboBox(self.project_frame)
self.project_dropdown.setMinimumSize(20, 0)
self.project_refresh = QToolButton(self.project_frame)
self.project_refresh.setText('Refresh')
self.project_frame_layout.addWidget(self.project_dropdown)
self.project_frame_layout.addWidget(self.project_refresh)
self.project_frame.setLayout(self.project_frame_layout)
self.panel_frame = QFrame(self)
self.panel_frame_layout = QVBoxLayout(self.panel_frame)
for panel in panels:
self.panel_frame_layout.addWidget(panel)
self.panel_frame.setLayout(self.panel_frame_layout)
self.bottom_frame = QFrame(self)
self.bottom_frame_layout = QHBoxLayout(self.bottom_frame)
self.bottom_frame_layout.addStretch()
self.sg_button = QToolButton()
self.sg_button.setText('Extra Stuff')
self.bottom_frame_layout.addWidget(self.sg_button)
self.bottom_frame.setLayout(self.bottom_frame_layout)
self.log = QTextEdit()
self.log_frame = QFrame(self)
self.log_frame_layout = QHBoxLayout(self.log_frame)
self.log_frame_layout.addWidget(self.log)
self.log_frame.setLayout(self.log_frame_layout)
self.main_layout.addWidget(self.toolbar_frame)
self.main_layout.addWidget(self.project_frame)
self.main_layout.addWidget(self.panel_frame)
self.main_layout.addWidget(self.bottom_frame)
self.app_widgets = QWidget(self)
self.app_widgets.setLayout(self.main_layout)
self.log_widget = QWidget(self)
self.log_widget.setLayout(self.log_frame_layout)
self.total_layout = QVBoxLayout(self)
self.total_layout.addWidget(self.app_widgets)
self.total_layout.addWidget(self.log_widget)
self.setLayout(self.total_layout)
self.log_button.clicked.connect(self.toggle_log)
def toggle_log(self):
if self.log_widget.isHidden():
self.log_widget.show()
QTimer.singleShot(0, self.resize_show)
else:
self.log_widget.hide()
QTimer.singleShot(0, self.resize_hide)
# self.adjustSize() Also does not work.
def resize_show(self):
self.resize(self.width(), self.sizeHint().height())
def resize_hide(self):
self.resize(self.width(), self.minimumSizeHint().height())
class AppPanel(QWidget):
def __init__(self, sections=[]):
super(AppPanel, self).__init__()
self.setSizePolicy(
QSizePolicy.MinimumExpanding,
QSizePolicy.MinimumExpanding
)
self.layout = QVBoxLayout(self)
self.setLayout(self.layout)
self.sections = sections
for section in self.sections:
self.layout.addWidget(section)
class AppSection(QWidget):
def __init__(self, buttons=[]):
super(AppSection, self).__init__()
self.setSizePolicy(
QSizePolicy.MinimumExpanding,
QSizePolicy.MinimumExpanding
)
self.buttons = buttons
self.layout = QGridLayout()
for i, button in enumerate(self.buttons):
col = i % 2
row = i // 2
self.layout.addWidget(button, row, col)
self.setLayout(self.layout)
class AppButton(QToolButton):
def __init__(self, text=''):
super(AppButton, self).__init__()
self.setText(text)
self.setFocusPolicy(Qt.NoFocus)
self.setIconSize(QSize(50, 50))
self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
if __name__ == '__main__':
app = QApplication(sys.argv)
app_buttons = [AppButton(text='APPS ' + str(i)) for i in range(5)]
custom_btns = [AppButton(text='Custom ' + str(i)) for i in range(5)]
app_section = AppSection(buttons=app_buttons)
custom_section = AppSection(buttons=custom_btns)
panels = [AppPanel(sections=[app_section, custom_section])]
ex = AppWidget(panels=panels)
lw = AppWindow(main_widget=ex)
lw.show()
app.exec_()
Resizing the widget alone is not a valid solution, because it only overrides the geometry set by the layout without notifying the parent widget.
This is also important as you should not resize the widget based on its hint alone when showing the log: if you increase the size of the window while the log is hidden and then show it again, it will not occupy all the available space.
What you need to do is to access the top level window, force its layout to lay out its contents again, and use its hint to for the resize.
def resize_hide(self):
self.window().layout().activate()
self.window().resize(
self.window().width(),
self.window().minimumSizeHint().height()
)
You can set the alignment policy for your top widget:
[...]
self.total_layout.setAlignment(self.app_widgets, Qt.AlignTop)
self.setLayout(self.total_layout)
[...]
The app_widget will not be resized anymore when you hide your text edit.

Adding animation to QPushbutton enterEvent and exitEvent

I'm trying to add custom animation to QPushbutton without making a custom QPushbutton and overriding its enterEvent() and leaveEvent().
So far I've tried this,
#staticmethod
def addButtonHoverAnimation(button:QPushButton,currentPos:QPoint):
'''
Method to:
=> Add hover animation for provided button
'''
enterShift = QPropertyAnimation(button,b'pos',button)
exitShift = QPropertyAnimation(button,b'pos',button)
def enterEvent(e):
pos=button.pos()
enterShift.setStartValue(pos)
enterShift.setEndValue(QPoint(pos.x()+3,pos.y()+3))
enterShift.setDuration(100)
enterShift.start()
Effects.dropShadow(button,1,2)
def leaveEvent(e):
pos=button.pos()
exitShift.setStartValue(pos)
exitShift.setEndValue(QPoint(pos.x()-3,pos.y()-3))
exitShift.setDuration(100)
exitShift.start()
Effects.dropShadow(button)
button.enterEvent=enterEvent
button.leaveEvent=leaveEvent
But when I move the mouse very quickly in and out of the button before the animation finishes, The button starts to move wierdly towards the North-West direction.
Button Animation Using Dynamic Positions
I figured out this was due to the leaveEvent() being triggered before enterEvent() even finishes and also because the start and end values are dynamic. So, I tried providing currentPos as a static position and using it instead,
#staticmethod
def addButtonHoverAnimation(button:QPushButton,currentPos:QPoint):
'''
Method to:
=> Add hover animation for provided button
'''
enterShift = QPropertyAnimation(button,b'pos',button)
enterShift.setStartValue(currentPos)
enterShift.setEndValue(QPoint(currentPos.x()+3,currentPos.y()+3))
enterShift.setDuration(100)
exitShift = QPropertyAnimation(button,b'pos',button)
exitShift.setStartValue(QPoint(currentPos.x()-3,currentPos.y()-3))
exitShift.setEndValue(currentPos)
exitShift.setDuration(100)
def enterEvent(e):
button.setProperty(b'pos',exitShift.endValue())
enterShift.start()
Effects.dropShadow(button,1,2)
def leaveEvent(e):
exitShift.start()
Effects.dropShadow(button)
button.enterEvent=enterEvent
button.leaveEvent=leaveEvent
On running, as soon as the mouse enters the QPushbutton, it moves to the top-left of its parent widget and the animation starts working fine. I can't figure out why this is happening. But I was able to get that, it only happened when I used any static value in the animation.
Button Animation with Static Position:
Here is an example:
import sys
from PyQt5.QtCore import QEvent, QPoint, QObject, QPropertyAnimation
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
# This is the same method mentioned above
from styling import addButtonHoverAnimation
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
layout=QVBoxLayout()
button1 = QPushButton("Proceed1", self)
layout.addWidget(button1)
button2 = QPushButton("Proceed2", self)
layout.addWidget(button2)
self.setLayout(layout)
self.resize(640, 480)
addButtonHoverAnimation(button1)
addButtonHoverAnimation(button2)
def main():
app = QApplication(sys.argv)
view = Widget()
view.show()
ret = app.exec_()
sys.exit(ret)
if __name__ == "__main__":
main()
The problem is that probably when the state is changed from enter to leave (or vice versa) the previous animation still does not end so the position of the widget is not the initial or final position, so when starting the new animation there is a deviation that accumulates. One possible solution is to initialize the position and keep it as a reference.
On the other hand you should not do x.fooMethod = foo_callable since many can fail, in this case it is better to use an eventfilter.
import sys
from dataclasses import dataclass
from functools import cached_property
from PyQt5.QtCore import QEvent, QPoint, QObject, QPropertyAnimation
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget
#dataclass
class AnimationManager(QObject):
widget: QWidget
delta: QPoint = QPoint(3, 3)
duration: int = 100
def __post_init__(self):
super().__init__(self.widget)
self._start_value = QPoint()
self._end_value = QPoint()
self.widget.installEventFilter(self)
self.animation.setTargetObject(self.widget)
self.animation.setPropertyName(b"pos")
self.reset()
def reset(self):
self._start_value = self.widget.pos()
self._end_value = self._start_value + self.delta
self.animation.setDuration(self.duration)
#cached_property
def animation(self):
return QPropertyAnimation(self)
def eventFilter(self, obj, event):
if obj is self.widget:
if event.type() == QEvent.Enter:
self.start_enter_animation()
elif event.type() == QEvent.Leave:
self.start_leave_animation()
return super().eventFilter(obj, event)
def start_enter_animation(self):
self.animation.stop()
self.animation.setStartValue(self.widget.pos())
self.animation.setEndValue(self._end_value)
self.animation.start()
def start_leave_animation(self):
self.animation.stop()
self.animation.setStartValue(self.widget.pos())
self.animation.setEndValue(self._start_value)
self.animation.start()
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
button1 = QPushButton("Proceed1", self)
button1.move(100, 100)
button2 = QPushButton("Proceed2", self)
button2.move(200, 200)
self.resize(640, 480)
animation_manager1 = AnimationManager(widget=button1)
animation_manager2 = AnimationManager(widget=button2)
def main():
app = QApplication(sys.argv)
view = Widget()
view.show()
ret = app.exec_()
sys.exit(ret)
if __name__ == "__main__":
main()
184 / 5000
Resultados de traducción
If you are using a layout then you must reset the position since the layout does not apply the position change immediately but only when the parent widget applies the changes.
class Widget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
button1 = QPushButton("Proceed1")
button2 = QPushButton("Proceed2")
lay = QVBoxLayout(self)
lay.addWidget(button1)
lay.addWidget(button2)
self.resize(640, 480)
self.animation_manager1 = AnimationManager(widget=button1)
self.animation_manager2 = AnimationManager(widget=button2)
def resizeEvent(self, event):
super().resizeEvent(event)
self.animation_manager1.reset()
self.animation_manager2.reset()

How to have signals and slots connect across classes?

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

PyQt changing specific button

I've been looking through answers for a while but couldn't find a solution to my problem. I recently started playing around with PyQt and trying to code out couple of ideas, one of which was to have a couple of buttons with some text on them and when a button is clicked, its text would change color. Here is my code:
import sys
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QMainWindow,
QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout, QMessageBox)
from PyQt5.QtCore import pyqtSlot, Qt
class App(QDialog):
def __init__(self):
super().__init__()
self.title = "Battleship"
self.left = 50
self.top = 50
self.width = 750
self.height = 500
self.initUI()
def initUI(self):
self.setGeometry(self.left, self.top, self.width, self.height)
self.setWindowTitle(self.title)
self.setFixedSize(self.width, self.height)
stylesheet = """QPushButton {background: #EEE; color: #11}
!QPushButton {background: #555; color: #EEE}"""
self.setStyleSheet(stylesheet)
self.grid()
layout = QVBoxLayout()
layout.addWidget(self.box)
self.setLayout(layout)
self.show()
def grid(self):
self.box = QGroupBox()
self.layout = QGridLayout()
self.box.setLayout(self.layout)
self.button1 = QPushButton('X', self)
self.button2 = QPushButton('X', self)
self.button3 = QPushButton('X', self)
self.button1.clicked.connect(self.pick)
self.button2.clicked.connect(self.pick)
self.button3.clicked.connect(self.pick)
self.layout.addWidget(self.button1)
self.layout.addWidget(self.button2)
self.layout.addWidget(self.button3)
def pick(self):
# turn 'X' from black to red ONLY on the clicked button
# while leaving the others untouched
pass
#---------------------------------------------------------------
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = App()
sys.exit(app.exec_())
What does the 'pick' function have to look like in order to do this? To clarify: I don't want to make three individual functions, one for each button (as it would be very impractical for a larger number of buttons), but a single function which would work with any button.
the sender() method returns us the object that emits the signal, in your case the button will be pressed:
def pick(self):
# turn 'X' from black to red ONLY on the clicked button
# while leaving the others untouched
btn = self.sender()
btn.setStyleSheet("color: red")

Categories

Resources