How can I show multiple pages in one window? - python

I'm currently creating a to-do application. I have a side menu (which is just QPushButtons in a vbox) and have a main window widget to show content. However, I need a way to show different content in the main widget based on what side menu button is pressed. I have tried to use QStackedLayout, but I don't like the way it closes the main window and switches to a new one. I've also tried to use QTabWidget, but the tabs are at the top. Is there a way to sub-class QTabWidget and create a custom QTabWidget with the tab buttons on the side? If not, is there a way to do this? The image above is what I have so far.
This is all my code:
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from datetime import date
import sys
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"]
stylesheet = """
QWidget{
background-color: white;
}
QWidget#sideMenuBackground{
background-color: #f7f7f7;
}
QVBoxLayout#sideMenuLayout{
background-color: grey;
}
QPushButton#sideMenuButton{
text-align: left;
border: none;
background-color: #f7f7f7;
max-width: 10em;
font: 16px;
padding: 6px;
}
QPushButton#sideMenuButton:hover{
font: 18px;
}
QLabel#today_label{
font: 25px;
max-width: 70px;
}
QLabel#todays_date_label{
font: 11px;
color: grey;
}
QPushButton#addTodoEventButton{
border: none;
max-width: 130px;
}
"""
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("To-Do Application")
self.setGeometry(200, 200, 800, 500)
self.initUI()
def initUI(self):
self.nextWeekPage = QtWidgets.QLabel()
backgroundWidget = QtWidgets.QWidget()
backgroundWidget.setObjectName("sideMenuBackground")
backgroundWidget.setFixedWidth(150)
layout = QtWidgets.QHBoxLayout()
layout.addWidget(backgroundWidget)
sideMenuLayout = QtWidgets.QVBoxLayout()
sideMenuLayout.setObjectName("sideMenuLayout")
taskLayout = QtWidgets.QVBoxLayout()
backgroundWidget.setLayout(sideMenuLayout)
layout.addLayout(taskLayout)
self.setSideMenu(sideMenuLayout)
sideMenuLayout.addStretch(0)
self.setMainLayout(taskLayout)
taskLayout.addStretch(0)
mainWidget = QtWidgets.QWidget()
mainWidget.setLayout(layout)
self.setCentralWidget(mainWidget)
def setSideMenu(self, layout):
self.todayButton = QtWidgets.QPushButton(" Today")
self.nextWeekButton = QtWidgets.QPushButton("Next 7 Days")
self.calendarButton = QtWidgets.QPushButton("Calendar")
sideMenuButtons = [self.todayButton, self.nextWeekButton, self.calendarButton]
for button in sideMenuButtons:
button.setObjectName("sideMenuButton")
layout.addWidget(button)
sideMenuButtons[0].setIcon(QtGui.QIcon("today icon.png"))
sideMenuButtons[1].setIcon(QtGui.QIcon("week icon.png"))
sideMenuButtons[2].setIcon(QtGui.QIcon("calendar icon.png"))
sideMenuButtons[0].pressed.connect(self.todayButtonPress)
sideMenuButtons[1].pressed.connect(self.nextWeekButtonPress)
sideMenuButtons[2].pressed.connect(self.calendarButtonPress)
def setMainLayout(self, layout):
today_label_widget = QtWidgets.QWidget()
today_label_layout = QtWidgets.QHBoxLayout()
layout.addWidget(today_label_widget)
today_label_widget.setLayout(today_label_layout)
month = date.today().month
day = date.today().day
today = f"{months[month - 1]}{day}"
self.todays_date = QtWidgets.QLabel(today)
self.todays_date.setObjectName("todays_date_label")
self.today_label = QtWidgets.QLabel("Today")
self.today_label.setObjectName("today_label")
self.addTodoEventButton = QtWidgets.QPushButton()
self.addTodoEventButton.setObjectName("addTodoEventButton")
self.addTodoEventButton.setIcon(QtGui.QIcon("add event button.png"))
self.addTodoEventButton.setToolTip("Add To Do Event")
today_label_layout.addWidget(self.today_label)
today_label_layout.addWidget(self.todays_date)
today_label_layout.addWidget(self.addTodoEventButton)
self.labels = ["button1", "button2", "button3", "button4", "Button5"]
for today_events in self.labels:
label = QtWidgets.QLabel(today_events)
layout.addWidget(label)
def addTodoEvent(self):
pass
def todayButtonPress(self):
print("today button pressed")
def nextWeekButtonPress(self):
print("Next week button pressed")
def calendarButtonPress(self):
print("calendar button pressed")
def main():
app = QtWidgets.QApplication(sys.argv)
app.setStyleSheet(stylesheet)
window = MainWindow()
window.show()
app.exec_()
if __name__ == "__main__":
main()

Using a stacked layout shouldn't open a new window when used correctly. The snippet below outlines how the original code could be adapted to use a stacked layout to open different pages in the same window.
class MainWindow(QtWidgets.QMainWindow):
def initUI(self):
# same as before
self.taskLayout = QtWidgets.QStackedLayout()
self.setMainLayout(self.taskLayout)
# same as before
def setMainLayout(self, layout)
today = self.todayWidget()
next_week = self.nextWeekWidget()
calendar_widget = self.calendarWidget()
layout.addWidget(today)
layout.addWidget(next_week)
layout.addWidget(calendar_widget)
def todayWidget(self)
widget = QtWidgets.QWidget(self)
layout = QVBoxLayout(widget)
# setup layout for today's widget
return widget
def nextWeekWidget(self)
widget = QtWidgets.QWidget(self)
layout = QVBoxLayout(widget)
# setup layout for next week's widget
return widget
def calendarWidget(self)
widget = QtWidgets.QWidget(self)
layout = QVBoxLayout(widget)
# setup layout for calendar widget
return widget
def todayButtonPress(self):
self.taskLayout.setCurrentIndex(0)
def nextWeekButtonPress(self):
self.taskLayout.setCurrentIndex(1)
def calendarButtonPress(self):
self.taskLayout.setCurrentIndex(2)

Here is a solution using a custom QListWidget combined with a QStackedWidget.
QListWidget on the left and QStackedWidget on the right, then add a QWidget to it in turn.
When adding a QWidget on the right, there are two variants:
The list on the left is indexed according to the serial number. When adding a widget, the variable name with the serial number is indicated on the right, for example, widget_0, widget_1, widget_2, etc., so that it can be directly associated with the serial number QListWidget.
When an item is added to the list on the left side, the value of the corresponding widget variable is indicated on the right.
from random import randint
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QWidget, QListWidget, QStackedWidget,
QHBoxLayout, QListWidgetItem, QLabel)
class LeftTabWidget(QWidget):
def __init__(self, *args, **kwargs):
super(LeftTabWidget, self).__init__(*args, **kwargs)
self.resize(800, 600)
# Left and right layout (one QListWidget on the left + QStackedWidget on the right)
layout = QHBoxLayout(self, spacing=0)
layout.setContentsMargins(0, 0, 0, 0)
# List on the left
self.listWidget = QListWidget(self)
layout.addWidget(self.listWidget)
# Cascading window on the right
self.stackedWidget = QStackedWidget(self)
layout.addWidget(self.stackedWidget)
self.initUi()
def initUi(self):
# Initialization interface
# Switch the sequence number in QStackedWidget by the current item change of QListWidget
self.listWidget.currentRowChanged.connect(
self.stackedWidget.setCurrentIndex)
# Remove the border
self.listWidget.setFrameShape(QListWidget.NoFrame)
# Hide scroll bar
self.listWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
# Here we use the general text with the icon mode (you can also use Icon mode, setViewMode directly)
for i in range(5):
item = QListWidgetItem(
QIcon('Ok.png'), str('Option %s' % i), self.listWidget)
# Set the default width and height of the item (only height is useful here)
item.setSizeHint(QSize(16777215, 60))
# Text centered
item.setTextAlignment(Qt.AlignCenter)
# Simulate 5 right-side pages (it won't loop with the top)
for i in range(5):
label = QLabel('This is the page %d' % i, self)
label.setAlignment(Qt.AlignCenter)
# Set the background color of the label (randomly here)
# Added a margin margin here (to easily distinguish between QStackedWidget and QLabel colors)
label.setStyleSheet('background: rgb(%d, %d, %d); margin: 50px;' % (
randint(0, 255), randint(0, 255), randint(0, 255)))
self.stackedWidget.addWidget(label)
# style sheet
Stylesheet = """
QListWidget, QListView, QTreeWidget, QTreeView {
outline: 0px;
}
QListWidget {
min-width: 120px;
max-width: 120px;
color: white;
background: black;
}
QListWidget::item:selected {
background: rgb(52, 52, 52);
border-left: 2px solid rgb(9, 187, 7);
}
HistoryPanel::item:hover {background: rgb(52, 52, 52);}
QStackedWidget {background: rgb(30, 30, 30);}
QLabel {color: white;}
"""
if __name__ == '__main__':
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
app.setStyleSheet(Stylesheet)
w = LeftTabWidget()
w.show()
sys.exit(app.exec_())

Related

Is there a way to stack widgets and ignore overlapping?

I'm making a GUI using PyQt5 and I made the background of my widgets change color when you hover your mouse over them. However, when I hover over a widget, the widget beneath it overlaps and the background is cut off at the bottom.
Its because of the way I made the background, I had to space the widgets very close together and increase the border size in order to achieve that background effect, but it messes with the hover like I said before. Is there any way to ignore this overlapping, or perhaps a different method I could use to draw the background without having to overlap the widgets?
Here is a screenshot of what I want in case my explanation was bad (The bottom widget works fine because there is nothing beneath it to overlap)
I will also attach my code here so you can see what I did
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.layout = QVBoxLayout()
self.layout.addWidget(MyBar(self))
self.setLayout(self.layout)
self.layout.setContentsMargins(0,0,0,0)
self.setFixedSize(450,550)
self.setWindowFlags(Qt.FramelessWindowHint)
self.setStyleSheet('background-color: #121A2B;')
self.checkbox_style='''
QCheckBox
{
background-color : rgb(25,34,52);
border-radius : 5px;
spacing : 10px;
padding : 15px;
min-height : 15px;
}
QCheckBox::unchecked
{
color : rgb(159,172,168);
}
QCheckBox::checked
{
color : rgb(217,223,227);
}
QCheckBox::indicator
{
border : 2px solid rgb(105, 139, 194);
width : 12px;
height : 12px;
border-radius : 8px;
}
QCheckBox::indicator:checked
{
image : url(red.png);
border : 2px solid rgb(221, 54, 77);
}
QCheckBox::hover
{
background-color: #263450
}
'''
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(11)
font.setBold(True)
self.checkbox_layout = QVBoxLayout()
self.checkbox1 = QCheckBox('checkbox1')
self.checkbox_layout.addWidget(self.checkbox1)
self.checkbox1.setFont(font)
self.checkbox1.setStyleSheet(self.checkbox_style)
self.checkbox2 = QCheckBox('checkbox2')
self.checkbox_layout.addWidget(self.checkbox2)
self.checkbox2.setFont(font)
self.checkbox2.setStyleSheet(self.checkbox_style)
self.checkbox3 = QCheckBox('checkbox3')
self.checkbox_layout.addWidget(self.checkbox3)
self.checkbox3.setFont(font)
self.checkbox3.setStyleSheet(self.checkbox_style)
self.checkbox3 = QCheckBox('checkbox4')
self.checkbox_layout.addWidget(self.checkbox3)
self.checkbox3.setFont(font)
self.checkbox3.setStyleSheet(self.checkbox_style)
self.layout.addLayout(self.checkbox_layout)
self.checkbox_layout.setContentsMargins(15,7,290,350)
self.setLayout(self.layout)
self.layout.setAlignment(Qt.AlignTop)
class MyBar(QWidget):
def __init__(self, parent):
super(MyBar, self).__init__()
self.parent = parent
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.title = QLabel("")
font = QtGui.QFont()
font.setFamily("Bebas Neue")
font.setPointSize(25)
font.setBold(False)
self.title.setFont(font)
self.btn_close = QPushButton()
self.btn_close.clicked.connect(self.btn_close_clicked)
self.btn_close.setFixedSize(40, 35)
self.btn_close.setStyleSheet("QPushButton::hover"
"{"
"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #fc0703, stop: 1 #a10303);"
"border : none;"
"}"
"QPushButton"
"{"
"background-color : rgb(25, 34, 52)"
"}")
self.btn_close.setFlat(True)
self.btn_close.setIcon(QIcon("C:/Users/User/Documents/GitHub/guirebuild/close.png"))
self.btn_close.setIconSize(QSize(15, 15))
self.title.setFixedHeight(53)
self.title.setAlignment(Qt.AlignTop)
self.layout.addWidget(self.title)
self.layout.addWidget(self.btn_close,alignment=Qt.AlignTop)
self.title.setStyleSheet("""
background-color: rgb(25, 34, 52);
color: white;
""")
self.setLayout(self.layout)
self.start = QPoint(0, 0)
self.pressing = False
def resizeEvent(self, QResizeEvent):
super(MyBar, self).resizeEvent(QResizeEvent)
self.title.setFixedWidth(self.parent.width())
def mousePressEvent(self, event):
self.start = self.mapToGlobal(event.pos())
self.pressing = True
def mouseMoveEvent(self, event):
if self.pressing:
self.end = self.mapToGlobal(event.pos())
self.movement = self.end-self.start
self.parent.setGeometry(self.mapToGlobal(self.movement).x(),
self.mapToGlobal(self.movement).y(),
self.parent.width(),
self.parent.height())
self.start = self.end
def mouseReleaseEvent(self, QMouseEvent):
self.pressing = False
def btn_close_clicked(self):
self.parent.close()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
The problem is due to the stacking of new widgets, and the simplest solution would be to set a transparent background for those widgets if you're sure that they won't have a different background when not hovered:
self.checkbox_style='''
QCheckBox
{
background-color : rgb(0, 0, 0, 0);
...
Unfortunately, this will not really solve your problem, as there are serious logical issues in your implementation.
First of all, setting hardcoded content margins of a layout based on the overall layout is a serious problem for many reasons:
it forces you to change those hardcoded margins based on the menu contents;
it is based on your assumption about the current available fonts, which could potentially make the UI elements partially (or completely) hidden;
it doesn't allow you to properly add more objects to the layout;
After seriously considering the above matters (which are very important and should never be underestimated), the problem is that, while Qt allows to lay out items "outside" their possible position through QSS paddings, you need to consider the widget z-level, which by default stacks a new widget above any other previously created sibling widget (widgets that have a common ancestor), and that's why you see partially hidden check boxes.
The base solution would be to install an event filter, check if it's a HoverMove event type and then call raise_() to ensure that it's put above any other sibling:
class MainWindow(QWidget):
def __init__(self):
# ...
for check in self.findChildren(QCheckBox):
check.installEventFilter(self)
def eventFilter(self, obj, event):
if event.type() == event.HoverMove:
obj.raise_()
return super().eventFilter(obj, event)
Again, this will only partially solve your problem, as you'll soon find out that your hardcoded sizes and positions will not work well (remember, what you see on your screen is never what others see on theirs).
A possible solution would be to create a separate QWidget subclass for the menu, add checkboxes in there, and always compute the maximum height considering the padding. Then, to ensure that the widget box is properly put where it should you should add a addStretch() or at least a "main widget" (which is what is normally used for a "main window").
class Menu(QWidget):
padding = 15
def __init__(self):
super().__init__()
layout = QVBoxLayout(self)
self.setMaximumHeight(0)
layout.setContentsMargins(0, 15, 0, 15)
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(11)
font.setBold(True)
self.setFont(font)
self.setStyleSheet('''
QCheckBox
{
background-color : rgb(25,34,52);
border-radius : 5px;
spacing : 10px;
padding : 15px;
min-height : 15px;
}
QCheckBox::unchecked
{
color : rgb(159,172,168);
}
QCheckBox::checked
{
color : rgb(217,223,227);
}
QCheckBox::indicator
{
border : 2px solid rgb(105, 139, 194);
width : 12px;
height : 12px;
border-radius : 8px;
}
QCheckBox::indicator:checked
{
image : url(red.png);
border : 2px solid rgb(221, 54, 77);
}
QCheckBox::hover
{
background-color: #263450
}
''')
self.checks = []
def addOption(self, option):
checkBox = QCheckBox(option)
self.checks.append(checkBox)
checkBox.installEventFilter(self)
self.layout().addWidget(checkBox)
count = len(self.checks)
self.setMaximumHeight(count * checkBox.sizeHint().height() - 15)
def eventFilter(self, obj, event):
if event.type() == event.HoverMove:
obj.raise_()
return super().eventFilter(obj, event)
class MainWindow(QWidget):
def __init__(self):
# ...
self.menu = Menu()
self.layout.addWidget(self.menu, alignment=Qt.AlignTop)
for i in range(4):
self.menu.addOption('checkbox{}'.format(i + 1))
self.layout.addStretch()
Note that in the code above I still used an event filter while still using explicit opaque background colors, if you are fine with the parent background, you can avoid installing and using the event filter and only set the default background to the transparent rgb(0, 0, 0, 0).

update QStyle in EnterEvent

i wanna update the QStyle of the LineEdit while the mouse is in\out the widget (enterEvent\leaveEvent ) i tried to add a bool variable to the drawPrimitive function but i get this error
TypeError: drawPrimitive(self, QStyle.PrimitiveElement, QStyleOption, QPainter, widget: QWidget = None): 'a' is not a valid keyword argument
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PushButton_2 import Push_Button_
import sys
class LineEditStyle(QProxyStyle):
def drawPrimitive(self, element, option, painter, widget,a=None):
if a :
self.pen = QPen(QColor('green'))
else :
self.pen = QPen(QColor('red'))
self.pen.setWidth(4)
if element == QStyle.PE_FrameLineEdit:
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(self.pen)
painter.drawRoundedRect(QRect(0,0,400,40), 10, 10)
else:
super().drawPrimitive(element, option, painter, widget)
class LineEdit(QLineEdit):
def __init__(self,*args,**kwargs):
QLineEdit.__init__(self,*args,**kwargs)
self.a = 0
def enterEvent(self, a0):
self.a = 1
def leaveEvent(self, a0):
self.a = 0
def paintEvent(self,event):
option = QStyleOption()
option.initFrom(self)
self.style().drawPrimitive(QStyle.PE_FrameLineEdit,option,a=self.a)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
window.setGeometry(500,500,400,400)
window.setStyleSheet('background-color:#373737')
line = LineEdit(parent=window)
line.setGeometry(20,200,400,40)
style = LineEditStyle()
line.setStyle(style)
window.show()
sys.exit(app.exec())
You mustn't use the QStyleSheet with the QStyle because it makes a confusion and you have to set the default parameter Widget as None
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PushButton_2 import Push_Button_
import sys
class LineEditStyle(QProxyStyle):
def drawPrimitive(self, element, option, painter, widget=None,a=None):
if a :
self.pen = QPen(QColor('green'))
else :
self.pen = QPen(QColor('red'))
self.pen.setWidth(4)
if element == QStyle.PE_FrameLineEdit:
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(self.pen)
painter.drawRoundedRect(QRect(0,0,400,40), 10, 10)
else:
super().drawPrimitive(element, option, painter, widget)
def subElementRect(self, element, option, widget):
if element == QStyle.SE_LineEditContents :
return QRect(0,0,50,30)
else :
return super().subElementRect(element, option, widget)
def drawItemText(self, painter, rect, flags, pal, enabled, text, textRole):
rect_ = QRect(20,20,50,50)
text = text.upper()
painter.drawText(text,rect_,Qt.AlignCenter)
class LineEdit(QLineEdit):
def __init__(self,*args,**kwargs):
QLineEdit.__init__(self,*args,**kwargs)
self.a = 0
def enterEvent(self, a0):
self.a = 1
def leaveEvent(self, a0):
self.a = 0
def paintEvent(self,event):
option = QStyleOption()
option.initFrom(self)
painter = QPainter(self)
self.style().drawPrimitive(QStyle.PE_FrameLineEdit,option,painter,a=self.a)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
window.setGeometry(500,500,400,400)
#window.setStyleSheet('background-color:#373737')
line = LineEdit(parent=window)
line.setGeometry(20,200,400,40)
style = LineEditStyle()
line.setStyle(style)
window.show()
sys.exit(app.exec())
You might find QStyleSheets useful for something like this.
I mocked this up in Qt Designer by entering the following in styleSheet property (in code you would do mywidget.setStyleSheet('<parameters>') ):
QLineEdit {
border: 3px solid red;
}
QLineEdit:focus {
border: 3px solid green;
}
Edit: styleSheet string above works on focus, but the original question was about enterEvent/leaveEvent, which trigger on mouse hover. As #musicamente rightfully points out, to work on mouse hover the :hover pseudo state can be used instead of :focus:
QLineEdit {
border: 3px solid red;
}
QLineEdit:hover {
border: 3px solid green;
}
I made a QMainWindow with 2 QLineEdits: 1 has styleSheet set and the other is default. When the focus moves to the regular QLineEdit, the modified QLineEdit turns red.
You can make ALL of the QLineEdits behave the same by editing the styleSheet of their parent. In your case, you could use window.setStyleSheet('..... Here's another mockup in Qt Designer:

Custom QPushButton inside QStyledItemDelegate

Problem:
I'm able to add a QPushButton to a QStyledItemDelegate just fine. I'm faking the button press inside the delegate's editorEvent method so when you press it an action happens. I'm having trouble getting my QPushButton's style sheet working though- It only reads the first background parameter which is "red" and doesn't change on mouse hover or press.
It's unclear how I should go about setting up button click and hover detection to make the button act like a real button on the delegate. Do I need to set up an eventFilter? Should I do this at the view level? Do I do this inside the delegate's paint method? A combination of everything?
Goals:
Mouse hover over the list time will show the button button's icon.
Mouse hover over the button will change its background color.
Mouse clicks on the button will darken the background color to show a a click happened.
I'd like to set these parameters in a style sheet if possible, but I also don't mind doing it all within a paint function. Whatever works!
Current implementation
The button widget is red with a folder icon. The items correctly change color on select and hover (I want to keep that), but the item's buttons don't change at all.
Thanks!
Here's what I've put together so far:
import sys
from PySide2 import QtCore
from PySide2 import QtGui
from PySide2 import QtWidgets
class DelegateButton(QtWidgets.QPushButton):
def __init__(self, parent=None):
super(DelegateButton, self).__init__(parent)
# self.setLayout(QHBoxLayout())
size = 50
self.setFixedSize(size, size)
self.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_DialogOpenButton))
self.setStyleSheet("""
QPushButton{
background:red;
height: 30px;
font: 12px "Roboto Thin";
border-radius: 25
}
QPushButton:hover{
background: green;
}
QPushButton:hover:pressed{
background: blue;
}
QPushButton:pressed{
background: yellow;
}
""")
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.resize(300, 300)
# Model/View
entries = ['one', 'two', 'three']
model = QtGui.QStandardItemModel()
delegate = ListItemDelegate()
self.listView = QtWidgets.QListView(self)
self.listView.setModel(model)
self.listView.setItemDelegate(delegate)
for i in entries:
item = QtGui.QStandardItem(i)
model.appendRow(item)
# Layout
main_layout = QtWidgets.QVBoxLayout()
main_layout.addWidget(self.listView)
self.setLayout(main_layout)
# Connections
delegate.delegateButtonPressed.connect(self.on_delegate_button_pressed)
def on_delegate_button_pressed(self, index):
print('"{}" delegate button pressed'.format(index.data(QtCore.Qt.DisplayRole)))
class ListItemDelegate(QtWidgets.QStyledItemDelegate):
delegateButtonPressed = QtCore.Signal(QtCore.QModelIndex)
def __init__(self):
super(ListItemDelegate, self).__init__()
self.button = DelegateButton()
def sizeHint(self, option, index):
size = super(ListItemDelegate, self).sizeHint(option, index)
size.setHeight(50)
return size
def editorEvent(self, event, model, option, index):
# Launch app when launch button clicked
if event.type() == QtCore.QEvent.MouseButtonRelease:
click_pos = event.pos()
rect_button = self.rect_button
if rect_button.contains(click_pos):
self.delegateButtonPressed.emit(index)
return True
else:
return False
else:
return False
def paint(self, painter, option, index):
spacing = 10
icon_size = 40
# Item BG #########################################
painter.save()
if option.state & QtWidgets.QStyle.State_Selected:
painter.setBrush(QtGui.QColor('orange'))
elif option.state & QtWidgets.QStyle.State_MouseOver:
painter.setBrush(QtGui.QColor('black'))
else:
painter.setBrush(QtGui.QColor('purple'))
painter.drawRect(option.rect)
painter.restore()
# Item Text ########################################
rect_text = option.rect
QtWidgets.QApplication.style().drawItemText(painter, rect_text, QtCore.Qt.AlignVCenter | QtCore.Qt.AlignLeft, QtWidgets.QApplication.palette(), True, index.data(QtCore.Qt.DisplayRole))
# Custom Button ######################################
self.rect_button = QtCore.QRect(
option.rect.right() - icon_size - spacing,
option.rect.bottom() - int(option.rect.height() / 2) - int(icon_size / 2),
icon_size,
icon_size
)
option = QtWidgets.QStyleOptionButton()
option.initFrom(self.button)
option.rect = self.rect_button
# Button interactive logic
if self.button.isDown():
option.state = QtWidgets.QStyle.State_Sunken
else:
pass
if self.button.isDefault():
option.features = option.features or QtWidgets.QStyleOptionButton.DefaultButton
option.icon = self.button.icon()
option.iconSize = QtCore.QSize(30, 30)
painter.save()
self.button.style().drawControl(QtWidgets.QStyle.CE_PushButton, option, painter, self.button)
painter.restore()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Try:
https://doc.qt.io/qt-4.8/qstyle.html#StateFlag-enum
import sys
import PySide.QtCore as core
import PySide.QtGui as gui
QPushButton#pushButton {
background-color: yellow;
}
QPushButton#pushButton:hover {
background-color: rgb(224, 255, 0);
}
QPushButton#pushButton:pressed {
background-color: rgb(224, 0, 0);
}
Your custom QStyledItemDelegate catches the mouse event, so that it is not passed to the QListView. So in the QStyledItemDelegate.editor(Event) one simply needs to add.
if event.type() == core.QEvent.MouseButtonPress:
return False
Now the selection is recognizable in the paint()-method using option.state & gui.QStyle.State_Selected.
if __name__ == '__main__':
app = gui.QApplication(sys.argv)
app.setStyleSheet('QListView::item:hover {background: none;}')
mw = gui.QMainWindow()
model = MyListModel()
view = gui.QListView()
view.setItemDelegate(MyListDelegate(parent=view))
view.setSpacing(5)
view.setModel(model)
mw.setCentralWidget(view)
mw.show()
sys.exit(app.exec_())
class MyListDelegate(gui.QStyledItemDelegate):
w = 300
imSize = 90
pad = 5
h = imSize + 2*pad
sepX = 10
def __init__(self, parent=None):
super(MyListDelegate, self).__init__(parent)
def paint(self, painter, option, index):
mouseOver = option.state in [73985, 73729]
if option.state & QStyle.State_MouseOver::
painter.fillRect(option.rect, painter.brush())
pen = painter.pen()
painter.save()
x,y = (option.rect.x(), option.rect.y())
dataRef = index.data()
pixmap = dataRef.pixmap()
upperLabel = dataRef.upperLabel()
lowerLabel = dataRef.lowerLabel()
if mouseOver:
newPen = gui.QPen(core.Qt.green, 1, core.Qt.SolidLine)
painter.setPen(newPen)
else:
painter.setPen(pen)
painter.drawRect(x, y, self.w, self.h)
painter.setPen(pen)
x += self.pad
y += self.pad
painter.drawPixmap(x, y, pixmap)
font = painter.font()
textHeight = gui.QFontMetrics(font).height()
sX = self.imSize + self.sepX
sY = textHeight/2
font.setBold(True)
painter.setFont(font)
painter.drawText(x+sX, y-sY,
self.w-self.imSize-self.sepX, self.imSize,
core.Qt.AlignVCenter,
upperLabel)
font.setBold(False)
font.setItalic(True)
painter.setFont(font)
painter.drawText(x+sX, y+sY,
self.w-self.imSize-self.sepX, self.imSize,
core.Qt.AlignVCenter,
lowerLabel)
painter.restore()
def sizeHint(self, option, index):
return core.QSize(self.w, self.imSize+2*self.pad)
def editorEvent(self, event, model, option, index):
if event.type() == core.QEvent.MouseButtonRelease:
print 'Clicked on Item', index.row()
if event.type() == core.QEvent.MouseButtonDblClick:
print 'Double-Clicked on Item', index.row()
return True
window.button->setAutoFillBackground(false);
window.button->setAutoFillBackground(true);
window.button->setPalette(*palette_red);
Another Solution To Set CSS:
import sys
from PyQt5 import Qt as qt
class TopLabelNewProject(qt.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
layout = qt.QHBoxLayout(self)
layout.setContentsMargins(40, 0, 32, 0)
self.setLayout(layout)
self.setFixedHeight(80)
self.label = qt.QLabel("Dashboard")
layout.addWidget(self.label, alignment=qt.Qt.AlignLeft)
# self.newProjectButton = Buttons.DefaultButton("New project", self)
self.newProjectButton = qt.QPushButton("New project", self)
layout.addWidget(self.newProjectButton, alignment=qt.Qt.AlignRight)
style = '''
QWidget {
background-color: white;
}
QLabel {
font: medium Ubuntu;
font-size: 20px;
color: #006325;
}
QPushButton {
background-color: #006325;
color: white;
min-width: 70px;
max-width: 70px;
min-height: 70px;
max-height: 70px;
border-radius: 35px;
border-width: 1px;
border-color: #ae32a0;
border-style: solid;
}
QPushButton:hover {
background-color: #328930;
}
QPushButton:pressed {
background-color: #80c342;
}
'''
if __name__ == '__main__':
app = qt.QApplication(sys.argv)
app.setStyleSheet(style)
ex = TopLabelNewProject()
ex.show()
sys.exit(app.exec_())

PyQt5 StatusBar Separators

How do I add vertical separators to my statusbar?
(Red arrows) in this screenshot.
And if I success this how can I show selected Line and Column?
(Blue arrows) in same screenshot.
That's for windows.
void QStatusBar::addPermanentWidget(QWidget *widget, int stretch = 0)
Adds the given widget permanently to this status bar, reparenting the widget if it isn't already a child of this QStatusBar object. The stretch parameter is used to compute a suitable size for the given widget as the status bar grows and shrinks. The default stretch factor is 0, i.e giving the widget a minimum of space.
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QStatusBar, QLabel,
QPushButton, QFrame)
class VLine(QFrame):
# a simple VLine, like the one you get from designer
def __init__(self):
super(VLine, self).__init__()
self.setFrameShape(self.VLine|self.Sunken)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.statusBar().showMessage("bla-bla bla")
self.lbl1 = QLabel("Label: ")
self.lbl1.setStyleSheet('border: 0; color: blue;')
self.lbl2 = QLabel("Data : ")
self.lbl2.setStyleSheet('border: 0; color: red;')
ed = QPushButton('StatusBar text')
self.statusBar().reformat()
self.statusBar().setStyleSheet('border: 0; background-color: #FFF8DC;')
self.statusBar().setStyleSheet("QStatusBar::item {border: none;}")
self.statusBar().addPermanentWidget(VLine()) # <---
self.statusBar().addPermanentWidget(self.lbl1)
self.statusBar().addPermanentWidget(VLine()) # <---
self.statusBar().addPermanentWidget(self.lbl2)
self.statusBar().addPermanentWidget(VLine()) # <---
self.statusBar().addPermanentWidget(ed)
self.statusBar().addPermanentWidget(VLine()) # <---
self.lbl1.setText("Label: Hello")
self.lbl2.setText("Data : 15-09-2019")
ed.clicked.connect(lambda: self.statusBar().showMessage("Hello "))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

How to change QPushButton text and background color

I am using following code to connect QMenu to QPushButton. When button is clicked a pull-down menu with multiple sub-menu's items is shown.
button=QPushButton()
button.setText("Press Me")
font=QtGui.QFont()
button.setFont(font)
button.setSizePolicy(ToolButtonSizePolicy)
button.setPopupMode(QtGui.QToolButton.InstantPopup)
menu=QtGui.QMenu()
button.setMenu(menu)
menuItem1=menu.addAction('Menu Item1')
menuItem2=menu.addAction('Menu Item2')
Now depending on a condition I would like to customize QPushButton display by giving it a text and background color. The following line of code (which is supposed to change background color) has no effect on QPushButton connected to QMenu.
button.setStyleSheet('QPushButton {background-color: #A3C1DA}')
I would like to know how to change the background color of QPushButton as well as button's text's color.
Apart from some inconsistencies with your code example setting the background color and text color of a QPushButton works just fine with:
setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
Example (using PySide):
from PySide import QtGui
app = QtGui.QApplication([])
button = QtGui.QPushButton()
button.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
button.setText('Press Me')
menu = QtGui.QMenu()
menuItem1 = menu.addAction('Menu Item1')
menuItem2 = menu.addAction('Menu Item2')
button.setMenu(menu)
button.show()
app.exec_()
results in:
For those who still want to change color of button with the instruction
button.setStyleSheet('QPushButton {background-color: #A3C1DA}')
and not able to do so, just modify the above instruction to
button.setStyleSheet('QPushButton {background-color: #A3C1DA; border: none}')
And it will change the button color, so the trick is to remove the border
I would add a comment to Trilarions answer, but not enough rep..
I was able to use his suggestion, without removing borders by
self.show()
self.button.setStyleSheet('background-color: red;')
AFTER doing a .show()
on my application. not sure why after works but not before. If anyone can explain that would be great
Change the background color when mouse is over the button
self.button.setStyleSheet(
"QPushButton::hover{"
"background-color: #ffd2cf;"
"border: none;"
"}"
)
You can improve your button further:
self.button.setToolTip("Hell o World")
self.button.mousePressEvent = lambda v: self.button.setIconSize(QSize(25, 25))#incresing iconsize
self.button.mouseReleaseEvent = lambda v: self.button.setIconSize(QSize(20, 20))#resetting to original iconsize
self.button.setStyleSheet(
"QPushButton::hover{"
"background-color: #ffd2cf;"
"border: none;"
"}"
)
self.button.myIcon = QIcon("c:/users/user-name/Pictures/icons/delete-row.png")
self.button.setIcon(self.button.myIcon)
self.button.setIconSize(QSize(20, 20))#setting original icon size
Here's a generic DecorableButton:
from PySide6.QtWidgets import (QPushButton)
from PySide6.QtGui import (QIcon, QMouseEvent)
from PySide6.QtCore import (Qt, QSize)
class DecButton(QPushButton):
def __init__(self, text: str = None, size: QSize = None, iconPath: str = None,
iconSize: QSize = None, onPressIconSizeIncrease: QSize = None,
onFocusBackgroundColor: str = None, toolTip: str = None, parent=None, color=None):
super().__init__(parent=parent)
##initializing UI
self.initUI(text=text, size=size, iconPath=iconPath,
iconSize=iconSize, onPressIconSizeIncrease=onPressIconSizeIncrease,
onFocusBackgroundColor=onFocusBackgroundColor, toolTip=toolTip, color=color)
pass
def initUI(self, text: str = None, size: QSize = None, iconPath: str = None,
iconSize: QSize = None, onPressIconSizeIncrease: int = None,
onFocusBackgroundColor: str = None, toolTip: str = None, color: str = None):
if text is not None:
self.setText(text)
if size is not None:
self.setFixedSize(size)
if iconPath is not None:
self.buttonIcon = QIcon(iconPath)
self.setIcon(self.buttonIcon)
self.buttonIconSize = iconSize
if iconSize:
self.setIconSize(self.buttonIconSize)
self.onPressIconSizeIncrease = onPressIconSizeIncrease
if onFocusBackgroundColor is not None:
self.setStyleSheet(
"QPushButton::hover{"
f"background-color: {onFocusBackgroundColor};"
"border: none;"
"}"
)
if color is not None:
if onFocusBackgroundColor is None:
self.setStyleSheet(
"QPushButton{"
f"background-color: {color};"
"border: none;"
"}"
)
else:
self.setStyleSheet(
"QPushButton{"
f"background-color: {color};"
"border: none;"
"}"
"QPushButton::hover{"
f"background-color: {onFocusBackgroundColor};"
"border: none;"
"}"
)
self.setToolTip(toolTip)
def mousePressEvent(self, event: QMouseEvent) -> None:
super().mousePressEvent(event)
if self.onPressIconSizeIncrease:
self.setIconSize(self.onPressIconSizeIncrease)
def mouseReleaseEvent(self, event: QMouseEvent) -> None:
super().mouseReleaseEvent(event)
if self.onPressIconSizeIncrease:
self.setIconSize(self.buttonIconSize)
if __name__ == "__main__":
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout)
app = QApplication([])
widget = QWidget()
widget.layout = QHBoxLayout()
widget.button = DecButton(iconPath="c:/users/devpa/Pictures/icons/delete-row.png",
iconSize=QSize(25, 25), onPressIconSizeIncrease=QSize(30, 30),
size=QSize(35, 35), onFocusBackgroundColor='#facdcd', color='#fcf8f7')
widget.layout.addWidget(widget.button)
widget.setLayout(widget.layout)
widget.show()
app.exec()
Output Window:
Changing button's text:
from PyQt5.QtWidgets import QPushButton
button = QPushButton("Some text")
button.setText('New text')
Changing button's background color:
from PyQt5.QtWidgets import QPushButton
button = QPushButton("Some text")
button1.setStyleSheet("background-color: red");
# or
# button2.setStyleSheet("background-color:#ff0000;");
# or
# button3.setStyleSheet("background-color:rgb(255,0,0)");

Categories