QFont.setFamily() not working with custom font - python

I was trying to make nice GUI for my program and I knew I needed a cool font as well. So I installed the 'Ubuntu' font with all weights.
But when I try this:
class MenuButton(QPushButton):
def __init__(self, caption):
super().__init__()
self.setFixedHeight(60)
self.setFixedWidth(100)
self.setFlat(True)
font = QFont()
font.setFamily('Ubuntu')
font.setWeight(QFont.Bold)
font.setPixelSize(20)
self.setFont(font)
self.setStyleSheet("color: rgb(85,170,255);")
self.setText(caption)
I get a font which pretty sure isn't what I picked:
But when I summon a QFontDialog at the start of my app however, I can see Ubuntu font and it IS named Ubuntu!
Why isn't it working and what am I supposed to do for it to work?
Appreciate the help...
Here is all:
import sys
import _thread
from PyQt5.QtCore import QSize, Qt, QRect, QObject
from PyQt5.QtWidgets import QApplication, QWidget, QProgressBar, QLabel, QTabWidget, QGridLayout, QVBoxLayout, \
QHBoxLayout, QSizePolicy, QSpacerItem, QStyle, QStyleFactory, QPushButton, QFrame, QFontDialog, QStackedWidget
from PyQt5.QtGui import QImage, QIcon, QPixmap, QPalette, QBrush, QColor, QFontDatabase, QFont
### Custom Classes
class MenuButton(QPushButton):
def __init__(self, caption):
super().__init__()
self.setFixedHeight(40)
self.setFixedWidth(100)
self.setFlat(True)
font = QFont()
font.setFamily('Ubuntu')
font.setWeight(QFont.Bold)
font.setPixelSize(19)
self.setFont(QFont('Ubuntu', 19, QFont.Medium))
self.setStyleSheet("color: rgb(85,170,255);")
self.setText(caption)
def select(self):
self.setStyleSheet("color: rgb(255,255,255);")
def deselect(self):
self.setStyleSheet("color: rgb(85,170,255);")
class StackPage(QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet('background-color: rgb(28,33,39)')
self.layout = QVBoxLayout()
self.setLayout(self.layout)
class MainScreen(QWidget):
def __init__(self):
super().__init__()
#self.windowWidth = 500
#self.windowHeight = 300
self.icon = 'images\\system\\HashshashinLogo.png'
self.title = 'DevOrder'
self.fontFamily = 'Segoe UI' # Corbel | Sagoe UI
self.fontColor = 'black'
self.fontSize = '12'
self.initUI()
def initUI(self):
self.setStyleSheet('font-family: %s; color: %s; background-color: rgb(28,33,39);' % (self.fontFamily, self.fontColor))
self.setWindowTitle(self.title)
self.setWindowIcon(QIcon(self.icon))
#self.setFixedSize(self.windowWidth, self.windowHeight)
### Top Menu
def menubtnProjectsClicked():
menubtnProjects.select()
menubtnClients.deselect()
menubtnUpdates.deselect()
menubtnSettings.deselect()
self.leftStackMenu.setCurrentIndex(0)
def menubtnClientsClicked():
menubtnProjects.deselect()
menubtnClients.select()
menubtnUpdates.deselect()
menubtnSettings.deselect()
self.leftStackMenu.setCurrentIndex(1)
def menubtnUpdatesClicked():
menubtnProjects.deselect()
menubtnClients.deselect()
menubtnUpdates.select()
menubtnSettings.deselect()
self.leftStackMenu.setCurrentIndex(2)
def menubtnSettingsClicked():
menubtnProjects.deselect()
menubtnClients.deselect()
menubtnUpdates.deselect()
menubtnSettings.select()
self.leftStackMenu.setCurrentIndex(3)
menubtnProjects = MenuButton('Projects')
menubtnProjects.clicked.connect(menubtnProjectsClicked)
menubtnClients = MenuButton('Clients')
menubtnClients.clicked.connect(menubtnClientsClicked)
menubtnUpdates = MenuButton('Updates')
menubtnUpdates.clicked.connect(menubtnUpdatesClicked)
menubtnSettings = MenuButton('Settings')
menubtnSettings.clicked.connect(menubtnSettingsClicked)
### Left Menu
self.leftStackMenu = QStackedWidget()
self.leftStackMenu.setFixedWidth(500)
leftProjectsPage = StackPage()
leftProjectsPage.setStyleSheet('background-color: white;')
leftClientsPage = StackPage()
leftClientsPage.setStyleSheet('background-color: red;')
leftUpdatesPage = StackPage()
leftUpdatesPage.setStyleSheet('background-color: blue;')
leftSettingsPage = StackPage()
leftSettingsPage.setStyleSheet('background-color: yellow;')
self.leftStackMenu.addWidget(leftProjectsPage)
self.leftStackMenu.addWidget(leftClientsPage)
self.leftStackMenu.addWidget(leftUpdatesPage)
self.leftStackMenu.addWidget(leftSettingsPage)
### Placings
menuLayout = QHBoxLayout()
menuLayout.setContentsMargins(50, 10, 10, 10)
menuLayout.addWidget(menubtnProjects)
menuLayout.addWidget(menubtnClients)
menuLayout.addWidget(menubtnUpdates)
menuLayout.addWidget(menubtnSettings)
menuLayout.addSpacerItem(QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Minimum))
stacksLayout = QHBoxLayout()
stacksLayout.addWidget(self.leftStackMenu)
menuWidget = QWidget()
menuWidget.setStyleSheet('background-color: rgb(22,26,31);')
menuWidget.setLayout(menuLayout)
mainLayout = QVBoxLayout()
mainLayout.addWidget(menuWidget)
mainLayout.addLayout(stacksLayout)
mainLayout.addSpacerItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
mainLayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(mainLayout)
#self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
#print('Currently used style:', app.style().metaObject().className())
#print('Available styles:', QStyleFactory.keys())
app.setStyle(QStyleFactory().create('windowsvista'))
QFontDialog().getFont()
loadingScreen = LoadingScren()
sys.exit(app.exec_())

To solve your problem, we need to change slightly your code.
First you add this line code self.setFont(QtGui.QFont("Ubuntu", 20, QtGui.QFont.Bold)) under class MenuButton().
Remember to show mainwindow, that you would do by adding this code
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setStyle(QtWidgets.QStyleFactory().create('windowsvista'))
win = MainScreen()
win.show()
sys.exit(app.exec_())
Window with correct font after launch
The code
import sys
import _thread
from PyQt5 import QtCore, QtGui, QtWidgets
### Custom Classes
class MenuButton(QtWidgets.QPushButton):
def __init__(self, caption):
super(MenuButton, self).__init__()
self.setFlat(True)
self.setFont(QtGui.QFont("Ubuntu", 20, QtGui.QFont.Bold))
self.setStyleSheet("color: rgb(85,170,255);")
self.setText(caption)
def select(self):
self.setStyleSheet("color: rgb(255,255,255);")
def deselect(self):
self.setStyleSheet("color: rgb(85,170,255);")
class StackPage(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setStyleSheet('background-color: rgb(28,33,39)')
self.layout = QtWidgets.QVBoxLayout()
self.setLayout(self.layout)
class MainScreen(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MainScreen, self).__init__(parent)
#self.windowWidth = 500
#self.windowHeight = 300
self.icon = 'images\\system\\HashshashinLogo.png'
self.title = 'DevOrder'
self.fontFamily = 'Segoe UI' # Corbel | Sagoe UI
self.fontColor = 'black'
self.fontSize = '12'
self.initUI()
def initUI(self):
self.setStyleSheet('font-family: %s; color: %s; background-color: rgb(28,33,39);' % (self.fontFamily, self.fontColor))
self.setWindowTitle(self.title)
self.setWindowIcon(QtGui.QIcon(self.icon))
#self.setFixedSize(self.windowWidth, self.windowHeight)
### Top Menu
def menubtnProjectsClicked():
menubtnProjects.select()
menubtnClients.deselect()
menubtnUpdates.deselect()
menubtnSettings.deselect()
self.leftStackMenu.setCurrentIndex(0)
def menubtnClientsClicked():
menubtnProjects.deselect()
menubtnClients.select()
menubtnUpdates.deselect()
menubtnSettings.deselect()
self.leftStackMenu.setCurrentIndex(1)
def menubtnUpdatesClicked():
menubtnProjects.deselect()
menubtnClients.deselect()
menubtnUpdates.select()
menubtnSettings.deselect()
self.leftStackMenu.setCurrentIndex(2)
def menubtnSettingsClicked():
menubtnProjects.deselect()
menubtnClients.deselect()
menubtnUpdates.deselect()
menubtnSettings.select()
self.leftStackMenu.setCurrentIndex(3)
menubtnProjects = MenuButton('Projects')
menubtnProjects.clicked.connect(menubtnProjectsClicked)
menubtnClients = MenuButton('Clients')
menubtnClients.clicked.connect(menubtnClientsClicked)
menubtnUpdates = MenuButton('Updates')
menubtnUpdates.clicked.connect(menubtnUpdatesClicked)
menubtnSettings = MenuButton('Settings')
menubtnSettings.clicked.connect(menubtnSettingsClicked)
### Left Menu
self.leftStackMenu = QtWidgets.QStackedWidget()
self.leftStackMenu.setFixedWidth(500)
leftProjectsPage = StackPage()
leftProjectsPage.setStyleSheet('background-color: white;')
leftClientsPage = StackPage()
leftClientsPage.setStyleSheet('background-color: red;')
leftUpdatesPage = StackPage()
leftUpdatesPage.setStyleSheet('background-color: blue;')
leftSettingsPage = StackPage()
leftSettingsPage.setStyleSheet('background-color: yellow;')
self.leftStackMenu.addWidget(leftProjectsPage)
self.leftStackMenu.addWidget(leftClientsPage)
self.leftStackMenu.addWidget(leftUpdatesPage)
self.leftStackMenu.addWidget(leftSettingsPage)
### Placings
menuLayout = QtWidgets.QHBoxLayout()
menuLayout.setContentsMargins(50, 10, 10, 10)
menuLayout.addWidget(menubtnProjects)
menuLayout.addWidget(menubtnClients)
menuLayout.addWidget(menubtnUpdates)
menuLayout.addWidget(menubtnSettings)
menuLayout.addSpacerItem(QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum))
stacksLayout = QtWidgets.QHBoxLayout()
stacksLayout.addWidget(self.leftStackMenu)
menuWidget = QtWidgets.QWidget()
menuWidget.setStyleSheet('background-color: rgb(22,26,31);')
menuWidget.setLayout(menuLayout)
mainLayout = QtWidgets.QVBoxLayout()
mainLayout.addWidget(menuWidget)
mainLayout.addLayout(stacksLayout)
mainLayout.addSpacerItem(QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding))
mainLayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(mainLayout)
#self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setStyle(QtWidgets.QStyleFactory().create('windowsvista'))
win = MainScreen()
win.show()
sys.exit(app.exec_())

Related

Custom window with pyqT5 under Linux

I've made a program with pyQT5 on Windows which works great, but now I'm switching back to Linux and the program is buggy, when I move the window with the custom titlebar sometimes it jumps across the screen
I used this post to write the code:
Custom Titlebar with frame in PyQt5
Anyone can help me
Here is a simplified sample code:
import sys
from PyQt5.QtCore import QPoint
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel
from PyQt5.QtWidgets import QPushButton, QVBoxLayout, QWidget
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.layout.addStretch(-1)
self.setMinimumSize(800, 400)
self.setWindowFlags(Qt.FramelessWindowHint)
self.pressing = False
class MyBar(QWidget):
def __init__(self, parent):
super(MyBar, self).__init__()
self.parent = parent
print(self.parent.width())
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.title = QLabel("My Own Bar")
btn_size = 35
self.btn_close = QPushButton("x")
self.btn_close.clicked.connect(self.btn_close_clicked)
self.btn_close.setFixedSize(btn_size, btn_size)
self.btn_close.setStyleSheet("background-color: red;")
self.btn_min = QPushButton("-")
self.btn_min.clicked.connect(self.btn_min_clicked)
self.btn_min.setFixedSize(btn_size, btn_size)
self.btn_min.setStyleSheet("background-color: gray;")
self.btn_max = QPushButton("+")
self.btn_max.clicked.connect(self.btn_max_clicked)
self.btn_max.setFixedSize(btn_size, btn_size)
self.btn_max.setStyleSheet("background-color: gray;")
self.title.setFixedHeight(35)
self.title.setAlignment(Qt.AlignCenter)
self.layout.addWidget(self.title)
self.layout.addWidget(self.btn_min)
self.layout.addWidget(self.btn_max)
self.layout.addWidget(self.btn_close)
self.title.setStyleSheet("""
background-color: black;
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()
def btn_max_clicked(self):
self.parent.showMaximized()
def btn_min_clicked(self):
self.parent.showMinimized()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
I have no idea where the problem is, and I didn't test it under macOS

How do I programmatically change the parent of a layout

I want to be able to move a layout to another layout based on a user input. I have the following code which does not appear to work for me. If I switch lines 31 and 34 so that they operate on the widget rather than the layout then I get the expected behaviour but I am hoping to operate on all widgets within a layout by just moving the layout.
import sys
from PyQt5.QtWidgets import QPushButton, QWidget, QHBoxLayout, QLabel, QApplication, QVBoxLayout
class b(QWidget):
def __init__(self, name):
super(b, self).__init__()
self.layout = QVBoxLayout(self)
lbl_1 = QLabel(name)
self.layout.addWidget(lbl_1)
class a(QWidget):
def __init__(self):
super(a, self).__init__()
self.layout = QHBoxLayout(self)
self.widget_1 = b('widget 1')
self.widget_2 = b('widget 2')
self.layout.addWidget(self.widget_1)
self.layout.addWidget(self.widget_2)
self.button_layout = QHBoxLayout()
self.move_layout = QPushButton('Move to other layout')
self.move_layout.clicked.connect(lambda: self.move_button())
self.button_layout.addWidget(self.move_layout)
self.widget = 'widget_2'
self.widget_2.layout.addLayout(self.button_layout)
def move_button(self):
if self.widget == 'widget_2':
self.widget_1.layout.addLayout(self.button_layout)
self.widget = 'widget_1'
else:
self.widget_2.layout.addLayout(self.button_layout)
self.widget = 'widget_2'
print('moved widget to {}'.format(self.widget))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = a()
window.show()
sys.exit(app.exec_())
Edit: to clarify, In the example above, the layout I want to move (self.button_layout) is a child layout of self.widget_2.layout. When I click the pushbutton, I want the self.button_layout to be set as a child layout of self.widget_1.layout. Essentially it will do what the code below does but using addLayout instead of addWidget.
import sys
from PyQt5.QtWidgets import QPushButton, QWidget, QHBoxLayout, QLabel, QApplication, QVBoxLayout
class b(QWidget):
def __init__(self, name):
super(b, self).__init__()
self.layout = QVBoxLayout(self)
lbl_1 = QLabel(name)
self.layout.addWidget(lbl_1)
class a(QWidget):
def __init__(self):
super(a, self).__init__()
self.layout = QHBoxLayout(self)
self.widget_1 = b('widget 1')
self.widget_2 = b('widget 2')
self.layout.addWidget(self.widget_1)
self.layout.addWidget(self.widget_2)
self.button_layout = QHBoxLayout()
self.move_layout = QPushButton('Move to other layout')
self.move_layout.clicked.connect(lambda: self.move_button())
self.button_layout.addWidget(self.move_layout)
self.widget = 'widget_2'
self.widget_2.layout.addLayout(self.button_layout)
def move_button(self):
if self.widget == 'widget_2':
self.widget_1.layout.addWidget(self.move_layout)
self.widget = 'widget_1'
else:
self.widget_2.layout.addWidget(self.move_layout)
self.widget = 'widget_2'
print('moved widget to {}'.format(self.widget))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = a()
window.show()
sys.exit(app.exec_())
The problem is that if a layout has a parent then it cannot be changed as the error message indicates:
QLayout::addChildLayout: layout "" already has a parent
One possible solution is to remove the parent:
def move_button(self):
self.button_layout.setParent(None)
if self.widget == "widget_2":
self.widget_1.layout.addLayout(self.button_layout)
self.widget = "widget_1"
else:
self.widget_2.layout.addLayout(self.button_layout)
self.widget = "widget_2"
print("moved widget to {}".format(self.widget))
Another alternative is to place the layout in a QWidget that is the container and that place it in the required layout:
class a(QWidget):
def __init__(self):
super(a, self).__init__()
layout = QHBoxLayout(self)
self.widget_1 = b("widget 1")
self.widget_2 = b("widget 2")
layout.addWidget(self.widget_1)
layout.addWidget(self.widget_2)
self.container = QWidget()
container_layout = QHBoxLayout(self.container)
button = QPushButton("Move to other layout")
button.clicked.connect(self.move_button)
container_layout.addWidget(button)
self.widget = "widget_1"
self.move_button()
def move_button(self):
if self.widget == "widget_2":
self.widget_1.layout.addWidget(self.container)
self.widget = "widget_1"
else:
self.widget_2.layout.addWidget(self.container)
self.widget = "widget_2"
print("moved widget to {}".format(self.widget))

How can I generate the buttons and connect them to different functions? [duplicate]

This question already has answers here:
How do I assert the identity of a PyQt5 signal?
(2 answers)
Closed 2 years ago.
I've created a search engine in PyQt5, using the code below:
import sys
from PyQt5.QtWidgets import (
QWidget, QLineEdit, QLabel, QScrollArea, QMainWindow,
QApplication, QHBoxLayout, QVBoxLayout, QSpacerItem, QSizePolicy, QCompleter, QPushButton
)
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
tlist = ['thing1', 'thing2', 'thing3', 'thing4']
class Label(QWidget):
def __init__(self, name):
super(Label, self).__init__()
self.name = name
self.lbl = QLabel(self.name)
self.lbl.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
self.btn = QPushButton("Preview")
self.btn.setMaximumSize(QtCore.QSize(100,100))
self.btn.clicked.connect(self.printsignal)
self.hbox = QHBoxLayout()
self.hbox.addWidget(self.lbl)
self.hbox.addWidget(self.btn)
self.setLayout(self.hbox)
def show(self):
for labels in [self, self.lbl]:
labels.setVisible(True)
def hide(self):
for labels in [self, self.lbl]:
labels.setVisible(False)
def printsignal(self):
print("clicked")
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__()
self.controls = QWidget()
self.controlsLayout = QVBoxLayout()
self.widgets = []
for name in tlist:
item = Label(name)
self.controlsLayout.addWidget(item)
self.widgets.append(item)
spacer = QSpacerItem(1, 1, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.controlsLayout.addItem(spacer)
self.controls.setLayout(self.controlsLayout)
self.scroll = QScrollArea()
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.controls)
self.searchbar = QLineEdit()
self.searchbar.textChanged.connect(self.update_display)
self.completer = QCompleter(tlist)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.searchbar.setCompleter(self.completer)
container = QWidget()
containerLayout = QVBoxLayout()
containerLayout.addWidget(self.searchbar)
containerLayout.addWidget(self.scroll)
container.setLayout(containerLayout)
self.setCentralWidget(container)
self.setGeometry(600, 100, 800, 600)
self.setWindowTitle('Search Engine')
def update_display(self, text):
for widget in self.widgets:
if text.lower() in widget.name.lower():
widget.show()
else:
widget.hide()
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The problem I have is, all the buttons share the same function and I don't know how to make them have different signals, as they are generated automatically. Basically, if I run the code it will show up like
this:
and when I press any of the buttons, it will print "clicked" (as in printsignal function). What I want is a different function for each button. Is there a way to do that?
Normally you can use self.sender().text() to get text from QButton which generated signal.
But because you create own widget Label with QButton and QLabel and you want text from label so you can get directly self.name
def printsignal(self):
print("clicked", self.name)
eventually self.lbl.text()
def printsignal(self):
print("clicked", self.lbl.text())
Working code.
I removed show(), hide() because you don't need it
import sys
from PyQt5.QtWidgets import (
QWidget, QLineEdit, QLabel, QScrollArea, QMainWindow,
QApplication, QHBoxLayout, QVBoxLayout, QSpacerItem, QSizePolicy, QCompleter, QPushButton
)
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
tlist = ['thing1', 'thing2', 'thing3', 'thing4']
class Label(QWidget):
def __init__(self, name):
super().__init__()
self.name = name
self.lbl = QLabel(self.name)
self.lbl.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
self.btn = QPushButton("Preview")
self.btn.setMaximumSize(QtCore.QSize(100,100))
self.btn.clicked.connect(self.printsignal)
self.hbox = QHBoxLayout()
self.hbox.addWidget(self.lbl)
self.hbox.addWidget(self.btn)
self.setLayout(self.hbox)
def printsignal(self):
print("clicked", self.name)
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__()
self.controls = QWidget()
self.controlsLayout = QVBoxLayout()
self.widgets = []
for name in tlist:
item = Label(name)
self.controlsLayout.addWidget(item)
self.widgets.append(item)
spacer = QSpacerItem(1, 1, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.controlsLayout.addItem(spacer)
self.controls.setLayout(self.controlsLayout)
self.scroll = QScrollArea()
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(True)
self.scroll.setWidget(self.controls)
self.searchbar = QLineEdit()
self.searchbar.textChanged.connect(self.update_display)
self.completer = QCompleter(tlist)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.searchbar.setCompleter(self.completer)
container = QWidget()
containerLayout = QVBoxLayout()
containerLayout.addWidget(self.searchbar)
containerLayout.addWidget(self.scroll)
container.setLayout(containerLayout)
self.setCentralWidget(container)
self.setGeometry(600, 100, 800, 600)
self.setWindowTitle('Search Engine')
def update_display(self, text):
for widget in self.widgets:
if text.lower() in widget.name.lower():
widget.show()
else:
widget.hide()
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

PyQt5 Custom Title Bar Doesn't Show

I am trying to make my first program. I'm hoping for custom dark mode design, and that requires me to make a custom title bar.
I copied the code for the title bar from someone else, it worked perfectly - custom movable window.
I have carefully merged it with my previous code, though title bar doesn't appear.
Now my guess is I have to call it at the end of my code, but it ends up with errors, as I'm not sure how to properly call it.
Note: removing the QtCore.Qt.FramelessWindowHint part is NOT the answer, as it just brings back the stock Win title bar, that's supposed to be hidden and replaced by dark title bar.
Part of code copied from: https://stackoverflow.com/a/44249552/12221725
Image:
import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QTextEdit
#fCol = "#e0e0e0"
#bCol = "#212121"
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.layout = QHBoxLayout()
self.textArea = QTextEdit("Lorem ipsum...")
self.layout.addWidget(self.textArea)
self.textArea.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;}")
self.sans = QFont("Segoe UI",20)
self.textArea.setFont(self.sans)
self.btnLayout = QVBoxLayout()
self.btnLayout.addWidget(QPushButton("Open"))
self.btnLayout.addWidget(QPushButton("Setup"))
self.btnLayout.addWidget(QPushButton("Find"))
self.setStyleSheet("QPushButton {max-width:200px;color:#4fc3f7;background-color:#424242;border:2px solid #4fc3f7;border-radius:16px;font-size:35px;font-weight:bold;}" + "QPushButton:hover {color:#212121;background-color:#4fc3f7;}" + "QPushButton:pressed {color:white;background-color:#212121;border-color:white;}")
self.status = QTextEdit()
self.status.insertPlainText("Successfully loaded" + "\nOpen a file...")
self.status.setReadOnly(1)
self.status.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;font-size:14px;max-width:200px;}")
self.btnLayout.addWidget(self.status)
self.layout.addLayout(self.btnLayout)
self.setLayout(self.layout)
#self.setFixedSize(650, 320)
self.setFixedSize(800, 400)
self.setWindowTitle("Py Program")
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)# | QtCore.Qt.WindowStaysOnTopHint)
#self.layout.setContentsMargins(0,0,0,0)
#self.layout.addStretch(-1)
#self.pressing = False
print("MainWindow Loaded")
#self.show()
class MyBar(QWidget):
def __init__(self, parent):
super(MyBar, self).__init__()
self.parent = parent
print(self.parent.width())
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.title = QLabel("My Own Bar")
btn_size = 35
self.btn_close = QPushButton("x")
self.btn_close.clicked.connect(self.btn_close_clicked)
self.btn_close.setFixedSize(btn_size,btn_size)
self.btn_close.setStyleSheet("background-color: red;")
self.btn_min = QPushButton("-")
self.btn_min.clicked.connect(self.btn_min_clicked)
self.btn_min.setFixedSize(btn_size, btn_size)
self.btn_min.setStyleSheet("background-color: gray;")
self.btn_max = QPushButton("+")
self.btn_max.clicked.connect(self.btn_max_clicked)
self.btn_max.setFixedSize(btn_size, btn_size)
self.btn_max.setStyleSheet("background-color: gray;")
self.title.setFixedHeight(35)
self.title.setAlignment(Qt.AlignCenter)
self.layout.addWidget(self.title)
self.layout.addWidget(self.btn_min)
self.layout.addWidget(self.btn_max)
self.layout.addWidget(self.btn_close)
self.title.setStyleSheet("background-color: black;color: white;")
self.setLayout(self.layout)
self.start = QPoint(0, 0)
self.pressing = False
print("MyBar Loaded")
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()
def btn_max_clicked(self):
self.parent.showMaximized()
def btn_min_clicked(self):
self.parent.showMinimized()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon("icon.png"))
app.setStyleSheet("QWidget {background-color:#424242;border-radius:12px;}")
app.setFont(QFont("Consolas"))
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
The problem is that you have not created or placed a Bar() inside the window. You must also restructure your layout so that the titlebar is displayed at the top and your content at the bottom using a QVBoxLayout.
On the other hand I have improved the original titleBar so that it is not necessary to set the parent directly but instead use the window():
import sys
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QTextEdit, QLabel
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowFlags(Qt.FramelessWindowHint)
hlayout = QHBoxLayout()
self.textArea = QTextEdit("Lorem ipsum...")
hlayout.addWidget(self.textArea)
self.textArea.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;}")
self.sans = QFont("Segoe UI",20)
self.textArea.setFont(self.sans)
self.btnLayout = QVBoxLayout()
self.btnLayout.addWidget(QPushButton("Open"))
self.btnLayout.addWidget(QPushButton("Setup"))
self.btnLayout.addWidget(QPushButton("Find"))
self.setStyleSheet("QPushButton {max-width:200px;color:#4fc3f7;background-color:#424242;border:2px solid #4fc3f7;border-radius:16px;font-size:35px;font-weight:bold;}" + "QPushButton:hover {color:#212121;background-color:#4fc3f7;}" + "QPushButton:pressed {color:white;background-color:#212121;border-color:white;}")
self.status = QTextEdit()
self.status.insertPlainText("Successfully loaded" + "\nOpen a file...")
self.status.setReadOnly(1)
self.status.setStyleSheet("QTextEdit {color:white;background-color:#212121;border-radius:+16px;font-size:14px;max-width:200px;}")
self.btnLayout.addWidget(self.status)
self.setFixedSize(800, 400)
self.setWindowTitle("Py app")
hlayout.addLayout(self.btnLayout)
custom_titlebar = TitleBar()
lay = QVBoxLayout(self)
lay.addWidget(custom_titlebar)
lay.addLayout(hlayout)
class TitleBar(QWidget):
def __init__(self, parent=None):
super(TitleBar, self).__init__(parent)
self.title = QLabel("My Own Bar")
btn_size = 35
self.btn_close = QPushButton("x")
self.btn_close.clicked.connect(self.btn_close_clicked)
self.btn_close.setFixedSize(btn_size,btn_size)
self.btn_close.setStyleSheet("background-color: red;")
self.btn_min = QPushButton("-")
self.btn_min.clicked.connect(self.btn_min_clicked)
self.btn_min.setFixedSize(btn_size, btn_size)
self.btn_min.setStyleSheet("background-color: gray;")
self.btn_max = QPushButton("+")
self.btn_max.clicked.connect(self.btn_max_clicked)
self.btn_max.setFixedSize(btn_size, btn_size)
self.btn_max.setStyleSheet("background-color: gray;")
self.title.setFixedHeight(35)
self.title.setAlignment(Qt.AlignCenter)
self.title.setStyleSheet("background-color: black;color: white;")
lay = QHBoxLayout(self)
lay.setContentsMargins(0,0,0,0)
lay.addWidget(self.title)
lay.addWidget(self.btn_min)
lay.addWidget(self.btn_max)
lay.addWidget(self.btn_close)
self.pressing = False
self.dragPosition = QPoint()
def resizeEvent(self, QResizeEvent):
super(TitleBar, self).resizeEvent(QResizeEvent)
self.title.setFixedWidth(self.window().width())
def mousePressEvent(self, event):
self.start = event.globalPos()
self.pressing = True
def mouseMoveEvent(self, event):
if self.pressing:
self.end = event.globalPos()
delta = self.end - self.start
self.window().move(self.window().pos() + delta)
self.start = self.end
def mouseReleaseEvent(self, QMouseEvent):
self.pressing = False
def btn_close_clicked(self):
self.window().close()
def btn_max_clicked(self):
self.window().showMaximized()
def btn_min_clicked(self):
self.window().showMinimized()
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setWindowIcon(QIcon("icon.png"))
app.setStyleSheet("QWidget {background-color:#424242;border-radius:12px;}")
app.setFont(QFont("Consolas"))
mw = MainWindow()
mw.show()
sys.exit(app.exec_())

PyQt5 Switch between window after time in a loop

i use the code below, found on stackoverflow. i want to build a loop which getting started with a button on the main window. After clicked window2 should open for 30 seconds. then window3 should open for 30 seconds. then window2 should open and so on.
i make a slide methode but it wont work.
i try it with the window2() and window3() and slide() methode
what is my target?
i want a slideshow with the two window(window2 & window3) that alternate.
not more but it is an endless loop
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel)
class Window2(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window22222")
class Window3(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window333333")
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.pushButton = QPushButton("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.pushButton.clicked.connect(self.window2)
self.pushButton1 = QPushButton("Start", self)
self.pushButton1.move(20, 20)
self.pushButton1.setToolTip("<h3>Start the Session</h3>")
self.pushButton1.clicked.connect(self.slide)
self.main_window()
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
def window2(self): # <===
self.w2 = Window2()
self.w2.show()
time.sleep(5)
self.w3 = Window3()
self.w3.show()
self.w2.hide()
self.window3()
#self.hide()
def window3(self): # <===
self.w3 = Window3()
self.w3.show()
time.sleep(5)
self.w2 = Window2()
self.w2.show()
self.w3.hide()
self.window2()
#self.hide()
def slide(self):
print ("slide")
self.window2()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec())
Try it:
import sys
#import time
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel)
class Window2(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Window 22222")
class Window3(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Window 333333")
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top, self.left, self.width, self.height = 100, 100, 680, 500
self.flag = ...
self.pushButton = QPushButton("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.pushButton.clicked.connect(lambda: self.start_slide(True)) #(self.window2)
self.pushButton1 = QPushButton("Start", self)
self.pushButton1.move(20, 20)
self.pushButton1.setToolTip("<h3>Start the Session</h3>")
self.pushButton1.clicked.connect(lambda: self.start_slide(False))
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
self.main_window()
self.w2 = Window2()
self.w3 = Window3()
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.viewWindows)
def start_slide(self, flag):
self.timer.stop()
self.w3.hide()
self.w2.hide()
if flag: self.w2.show()
else: self.w3.show()
self.flag = not flag
self.timer.start(5000)
def viewWindows(self):
if self.flag:
self.w2.show()
self.w3.hide()
else:
self.w3.show()
self.w2.hide()
self.flag = not self.flag
def closeEvent(self, event):
self.w2.close()
self.w3.close()
self.close()
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

Categories