PyQt5 grabWindow captures black screen instead of the selected area - python

I have an application where I have a transparent window, I am capturing the screen underneath and then displaying the same once user release the left mouse button.
But the problem is I see only black screen, I tried saving the selected screenshot but still same black screen.
Here is my code :
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
from PyQt5 import QtGui as qtg
import sys
class MainWindow(qtw.QMainWindow):
def __init__(self, *arg, **kwargs):
super().__init__()
self.setWindowFlag(qtc.Qt.FramelessWindowHint)
self.setAttribute(qtc.Qt.WA_TranslucentBackground)
borderWidget = qtw.QWidget(objectName='borderWidget')
self.setCentralWidget(borderWidget)
bgd = self.palette().color(qtg.QPalette.Window)
bgd.setAlphaF(.005)
self.setStyleSheet('''
#borderWidget {{
border: 3px solid blue;
background: {bgd};
}}
'''.format(bgd=bgd.name(bgd.HexArgb)))
self.setGeometry(100, 100, 400, 300)
self.showFullScreen()
self.setCursor(qtc.Qt.CrossCursor)
self.begin = None
self.end = None
self.show()
def paintEvent(self, event):
if self.begin:
qpbox = qtg.QPainter(self)
br = qtg.QBrush(qtg.QColor(100, 10, 10, 40))
qpbox.setBrush(br)
qpbox.drawRect(qtc.QRect(self.begin, self.end))
# close on right click
def mouseReleaseEvent(self, QMouseEvent):
if QMouseEvent.button() == qtc.Qt.RightButton:
self.close()
elif QMouseEvent.button() == qtc.Qt.LeftButton:
screen = qtw.QApplication.primaryScreen()
img = screen.grabWindow(self.winId(), self.begin.x(), self.end.y(), self.end.x() - self.begin.x() , self.end.y()-self.begin.y())
img.save('screenshot.png', 'png')
self.setStyleSheet("")
self.central_widget = qtw.QWidget()
label = qtw.QLabel(self)
label.setPixmap(img)
self.resize(img.width(), img.height())
self.setCentralWidget(label)
def mousePressEvent(self, QMouseEvent):
if QMouseEvent.button() == qtc.Qt.LeftButton:
self.begin = QMouseEvent.pos()
self.end = QMouseEvent.pos()
self.update()
def mouseMoveEvent(self, QMouseEvent):
self.end = QMouseEvent.pos()
self.update()
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())

You're grabbing from the current window, not from the desktop. While what you see is the desktop (due to the transparency), specifying a window id results in grabbing only that window without considering the background composition or any other foreign window.
If you want to grab from the screen, you need to use the root window's id, which is 0.
Also note that:
the coordinates are wrong, as you used self.end for the y coordinate;
if the user selects a negative rectangle, the result is unexpected; you should use a normalized rectangle instead (which always have positive width and height);
you should hide the widget before properly taking the screenshot, otherwise you will also capture the darkened background of the capture area;
there's no need to always replace the central widget, just use an empty QLabel and change its pixmap;
an alpha value of 0.005 is practically pointless, just make it transparent;
the capture rectangle should be cleared after the screenshot has been taken;
class MainWindow(qtw.QMainWindow):
def __init__(self, *arg, **kwargs):
super().__init__()
self.setWindowFlags(self.windowFlags() | qtc.Qt.FramelessWindowHint)
self.setAttribute(qtc.Qt.WA_TranslucentBackground)
# use a QLabel
borderWidget = qtw.QLabel(objectName='borderWidget')
self.setCentralWidget(borderWidget)
self.setStyleSheet('''
#borderWidget {{
border: 3px solid blue;
background: transparent;
}}
''')
# pointless, you're showing the window in full screen
# self.setGeometry(100, 100, 400, 300)
# variables that are required for painting must be declared *before*
# calling any show* function; while this is generally not an issue,
# as painting will actually happen "later", it's conceptually wrong
# to declare a variable after it's (possibly) required by a function.
self.captureRect = None
self.showFullScreen()
self.setCursor(qtc.Qt.CrossCursor)
# unnecessary, you've already called showFullScreen
# self.show()
def paintEvent(self, event):
if self.captureRect:
qpbox = qtg.QPainter(self)
br = qtg.QBrush(qtg.QColor(100, 10, 10, 40))
qpbox.setBrush(br)
qpbox.drawRect(self.captureRect)
def mouseReleaseEvent(self, event):
if event.button() == qtc.Qt.RightButton:
self.close()
elif event.button() == qtc.Qt.LeftButton:
self.hide()
screen = qtw.QApplication.primaryScreen()
img = screen.grabWindow(0, *self.captureRect.getRect())
self.show()
img.save('screenshot.png', 'png')
self.setStyleSheet('')
self.centralWidget().setPixmap(img)
self.captureRect = None
def mousePressEvent(self, event):
if event.button() == qtc.Qt.LeftButton:
self.begin = event.pos()
self.captureRect = qtc.QRect(self.begin, qtc.QSize())
def mouseMoveEvent(self, event):
self.captureRect = qtc.QRect(self.begin, event.pos()).normalized()
self.update()
Note that I changed the event handler argument: QMouseEvent is a class, and even though you're using the module (so the actual Qt class would be qtg.QMouseEvent), that might be confusing and risky if you eventually decide to directly import classes; besides, only class and constant names should have capitalized names, not variables or functions.

Related

Drawing Line from QLabel to QLabel in PyQt

I'm fairly new to PyQt
I'm trying to drawing a line from 1 QLabel to another.
My 2 QLabel are located on another QLabel which acts as an image in my GUI.
I've managed to track the mouse event and move the label around, but I cannot draw the line between them using QPainter.
Thank you in advance :)
This is my MouseTracking class
class MouseTracker(QtCore.QObject):
positionChanged = QtCore.pyqtSignal(QtCore.QPoint)
def __init__(self, widget):
super().__init__(widget)
self._widget = widget
self.widget.setMouseTracking(True)
self.widget.installEventFilter(self)
#property
def widget(self):
return self._widget
def eventFilter(self, o, e):
if e.type() == QtCore.QEvent.MouseMove:
self.positionChanged.emit(e.pos())
return super().eventFilter(o, e)
This is my DraggableLabel class:
class DraggableLabel(QLabel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.LabelIsMoving = False
self.setStyleSheet("border-color: rgb(238, 0, 0); border-width : 2.0px; border-style:inset; background: transparent;")
self.origin = None
# self.setDragEnabled(True)
def mousePressEvent(self, event):
if not self.origin:
# update the origin point, we'll need that later
self.origin = self.pos()
if event.button() == Qt.LeftButton:
self.LabelIsMoving = True
self.mousePos = event.pos()
# print(event.pos())
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
# move the box
self.move(self.pos() + event.pos() - self.mousePos)
# print(event.pos())
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
print(event.pos())
def paintEvent(self, event):
painter = QPainter()
painter.setBrush(Qt.red)
# painter.setPen(qRgb(200,0,0))
painter.drawLine(10, 10, 200, 200)
This is my custom class for the QTabwigdet (since I need to control and track the position of 2 QLabels whenever the user add/insert a new Tab)
class DynamicTab(QWidget):
def __init__(self):
super(DynamicTab, self).__init__()
# self.count = 0
self.setMouseTracking(True)
self.setAcceptDrops(True)
self.bool = True
self.layout = QVBoxLayout(self)
self.label = QLabel()
self.layout.addChildWidget(self.label)
self.icon1 = DraggableLabel(parent=self)
#pixmap for icon 1
pixmap = QPixmap('icon1.png')
# currentTab.setLayout(QVBoxLayout())
# currentTab.layout.setWidget(QRadioButton())
self.icon1.setPixmap(pixmap)
self.icon1.setScaledContents(True)
self.icon1.setFixedSize(20, 20)
self.icon2 = DraggableLabel(parent=self)
pixmap = QPixmap('icon1.png')
# currentTab.setLayout(QVBoxLayout())
# currentTab.layout.setWidget(QRadioButton())
self.icon2.setPixmap(pixmap)
self.icon2.setScaledContents(True)
self.icon2.setFixedSize(20, 20)
#self.label.move(event.x() - self.label_pos.x(), event.y() - self.label_pos.y())
MainWindow and main method:
class UI_MainWindow(QMainWindow):
def __init__(self):
super(UI_MainWindow, self).__init__()
self.setWindowTitle("QHBoxLayout")
self.PictureTab = QTabWidget
def __setupUI__(self):
# super(UI_MainWindow, self).__init__()
self.setWindowTitle("QHBoxLayout")
loadUi("IIML_test2.ui", self)
self.tabChanged(self.PictureTab)
# self.tabChanged(self.tabWidget)
self.changeTabText(self.PictureTab, index=0, TabText="Patient1")
self.Button_ImportNew.clicked.connect(lambda: self.insertTab(self.PictureTab))
# self.PictureTab.currentChanged.connect(lambda: self.tabChanged(QtabWidget=self.PictureTab))
# self.tabWidget.currentChanged.connect(lambda: self.tabChanged(QtabWidget=self.tabWidget))
def tabChanged(self, QtabWidget):
QtabWidget.currentChanged.connect(lambda : print("Tab was changed to ", QtabWidget.currentIndex()))
def changeTabText(self, QTabWidget, index, TabText):
QTabWidget.setTabText(index, TabText)
def insertTab(self, QtabWidget):
# QFileDialog.getOpenFileNames(self, 'Open File', '.')
QtabWidget.addTab(DynamicTab(), "New Tab")
# get number of active tab
count = QtabWidget.count()
# change the view to the last added tab
currentTab = QtabWidget.widget(count-1)
QtabWidget.setCurrentWidget(currentTab)
pixmap = QPixmap('cat.jpg')
#currentTab.setLayout(QVBoxLayout())
#currentTab.layout.setWidget(QRadioButton())
# currentTab.setImage("cat.jpg")
currentTab.label.setPixmap(pixmap)
currentTab.label.setScaledContents(True)
currentTab.label.setFixedSize(self.label.width(), self.label.height())
tracker = MouseTracker(currentTab.label)
tracker.positionChanged.connect(self.on_positionChanged)
self.label_position = QtWidgets.QLabel(currentTab.label, alignment=QtCore.Qt.AlignCenter)
self.label_position.setStyleSheet('background-color: white; border: 1px solid black')
currentTab.label.show()
# print(currentTab.label)
#QtCore.pyqtSlot(QtCore.QPoint)
def on_positionChanged(self, pos):
delta = QtCore.QPoint(30, -15)
self.label_position.show()
self.label_position.move(pos + delta)
self.label_position.setText("(%d, %d)" % (pos.x(), pos.y()))
self.label_position.adjustSize()
# def SetupUI(self, MainWindow):
#
# self.setLayout(self.MainLayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
UI_MainWindow = UI_MainWindow()
UI_MainWindow.__setupUI__()
widget = QtWidgets.QStackedWidget()
widget.addWidget(UI_MainWindow)
widget.setFixedHeight(900)
widget.setFixedWidth(1173)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")
My concept: I have a DynamicTab (QTabWidget) which acts as a picture opener (whenever the user press Import Now). The child of this Widget are 3 Qlabels: self.label is the picture it self and two other Qlabels are the icon1 and icon2 which I'm trying to interact/drag with (Draggable Label)
My Problem: I'm trying to track my mouse movement and custom the painter to paint accordingly. I'm trying that out by telling the painter class to paint whenever I grab the label and move it with my mouse (Hence, draggable). However, I can only track the mouse position inside the main QLabel (the main picture) whenever I'm not holding or clicking my left mouse.
Any help will be appreciated here.
Thank you guys.
Painting can only happen within the widget rectangle, so you cannot draw outside the boundaries of DraggableLabel.
The solution is to create a further custom widget that shares the same parent, and then draw the line that connects the center of the other two.
In the following example I install an event filter on the two draggable labels which will update the size of the custom widget based on them (so that its geometry will always include those two geometries) and call self.update() which schedules a repainting. Note that since the widget is created above the other two, it might capture mouse events that are intended for the others; to prevent that, the Qt.WA_TransparentForMouseEvents attribute must be set.
class Line(QWidget):
def __init__(self, obj1, obj2, parent):
super().__init__(parent)
self.obj1 = obj1
self.obj2 = obj2
self.obj1.installEventFilter(self)
self.obj2.installEventFilter(self)
self.setAttribute(Qt.WA_TransparentForMouseEvents)
def eventFilter(self, obj, event):
if event.type() in (event.Move, event.Resize):
rect = self.obj1.geometry() | self.obj2.geometry()
corner = rect.bottomRight()
self.resize(corner.x(), corner.y())
self.update()
return super().eventFilter(obj, event)
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(painter.Antialiasing)
painter.setPen(QColor(200, 0, 0))
painter.drawLine(
self.obj1.geometry().center(),
self.obj2.geometry().center()
)
class DynamicTab(QWidget):
def __init__(self):
# ...
self.line = Line(self.icon1, self.icon2, self)
Notes:
to simplify things, I only use resize() (not setGeometry()), in this way the widget will always be placed on the top left corner of the parent and we can directly get the other widget's coordinates without any conversion;
the custom widget is placed above the other two because it is added after them; if you want to place it under them, use self.line.lower();
the painter must always be initialized with the paint device argument, either by using QPainter(obj) or painter.begin(obj), otherwise no painting will happen (and you'll get lots of errors in the output);
do not use layout.addChildWidget() (which is used internally by the layout), but the proper addWidget() function of the layout;
the stylesheet border syntax can be shortened with border: 2px inset rgb(238, 0, 0);;
the first lines of insertTab could be simpler: currentTab = DynamicTab() QtabWidget.addTab(currentTab, "New Tab");
currentTab.label.setFixedSize(self.label.size());
QMainWindow is generally intended as a top level widget, it's normally discouraged to add it to a QStackedWidget; note that if you did that because of a Youtube tutorial, that tutorial is known for suggesting terrible practices (like the final try/except block) which should not be followed;
only classes and constants should have capitalized names, not variables and functions which should always start with a lowercase letter;

Can I make a PyQt5 rect fully transparent?

I am making an imitation of the built-in Win+Shift+S screenshot function on windows. I am not very familiar with QPainter. Just like the windows function, I want to darken the background, but highlight the actual selected rect the user does. Everything works, but since the background is dark the actual image is darkened. Is there a workaround for this?
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt, QPoint, QRect, Qt
from PyQt5.QtGui import QPixmap, QPen, QPainter, QColor, QBrush
from win32api import GetSystemMetrics, GetKeyState, GetCursorPos
import pyautogui
import PIL
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(GetSystemMetrics(0), GetSystemMetrics(1))
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground, True)
self.setWindowOpacity(.9)
self.setWindowFlag(Qt.Tool)
self.pix = QPixmap(self.rect().size())
(self.begin, self.destination) = (QPoint(), QPoint())
def paintEvent(self, event):
painter = QPainter(self)
painter.setOpacity(0.2)
painter.setBrush(Qt.black) #ACTUAL BACKGROUDN
painter.setPen(QPen(Qt.white)) #BORDER OF THE RECTANGLE
painter.drawRect(self.rect())
painter.drawPixmap(QPoint(), self.pix)
if not self.begin.isNull() and not self.destination.isNull():
rect = QRect(self.begin, self.destination)
painter.drawRect(rect.normalized())
def mousePressEvent(self, event):
global initial_x, initial_y
initial_x, initial_y = GetCursorPos()
print('down')
if event.buttons() & Qt.LeftButton:
self.begin = event.pos()
self.destination = self.begin
self.update()
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton:
self.destination = event.pos()
self.update()
def mouseReleaseEvent(self, event):
final_x, final_y = GetCursorPos()
print('up')
a = pyautogui.screenshot(region=(initial_x,initial_y, (final_x - initial_x), (final_y - initial_y)))
a.save(r'C:\Users\ohtitus\Documents\New folder\main.png')
if event.button() & Qt.LeftButton:
rect = QRect(self.begin, self.destination)
painter = QPainter(self.pix)
painter.drawRect(rect.normalized())
painter.fillRect(rect, QColor(0,0,0,0))
(self.begin, self.destination) = (QPoint(), QPoint())
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setOverrideCursor(Qt.CrossCursor)
app.setStyleSheet("background-color: rgb(0, 0, 0)")
app.setStyleSheet('''
QWidget {
font-size: 30px;
}
''')
myApp = MyApp()
myApp.show()
try:
sys.exit(app.exec_())
except SystemExit:
pass
In your paintEvent(self, event) method, add two lines of code before drawing the transparent rectangle which specifies the region to be captured
if not self.begin.isNull() and not self.destination.isNull():
painter.setOpacity(0.0) # Added
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) # Added
rect = QRect(self.begin, self.destination)
painter.drawRect(rect.normalized()) # Origianl code
So paintEvent(self, event) will look like this
def paintEvent(self, event):
painter = QPainter(self)
painter.setOpacity(0.2)
painter.setBrush(Qt.black) # ACTUAL BACKGROUDN
painter.setPen(QPen(Qt.white)) # BORDER OF THE RECTANGLE
painter.drawRect(self.rect())
painter.drawPixmap(QPoint(), self.pix)
if not self.begin.isNull() and not self.destination.isNull():
painter.setOpacity(0.0)
painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source)
rect = QRect(self.begin, self.destination)
painter.drawRect(rect.normalized())
Code explanation
painter.setOpacity(0.0) needs to draw a transparent figure
painter.setCompositionMode( mode ) changes the way how a new figure (source) will be merged into the the original drawing (destination).
By default, it is set to CompositionMode.CompositionMode_SourceOver, the mode where a source will overwrite a destination while the destiantion still appear in a transparent region of the source.
In your case, you want to make some part of the destination transparent . You can achieve this by making transparent source to overwrite the destination. The mode CompositionMode.CompositionMode_Source does it.
Refer to https://doc.qt.io/archives/qt-4.8/qpainter.html#CompositionMode-enum for more information about the composition mode.

PyQt5 Laying Properly

I've already looked heavily to see how to properly layer my ui and haven't found out how to layer my windows so it comes off looking somewhat like this:
I want to have my background layer which I have set as a label with an image and then have a qt widget with login centered in the middle of it almost popping out at the user however when I do this it comes out with the widget behind my main window, it doesn't align properly and it also doesnt "follow" the window when I move it around image provided:
import PyQt5.QtWidgets
import sys
class LoginPanel(PyQt5.QtWidgets.QWidget):
def __init__(self):
PyQt5.QtWidgets.QWidget.__init__(self)
self.setFixedSize(600,400)
self.setWindowFlags(PyQt5.QtCore.Qt.FramelessWindowHint | PyQt5.QtCore.Qt.WindowStaysOnTopHint)
self.setStyleSheet("""
QWidget {
background-color: #CBCAB7;
border-radius: 50px;
}
""")
self.show()
class Auth(PyQt5.QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Login")
self.setFixedSize(1200,800)
self.setWindowFlags(PyQt5.QtCore.Qt.WindowCloseButtonHint | PyQt5.QtCore.Qt.WindowMinimizeButtonHint)
self.setWindowIcon(PyQt5.QtGui.QIcon("assets\\login.ico"))
self.background = PyQt5.QtWidgets.QLabel("", self)
self.layout = PyQt5.QtWidgets.QGridLayout()
self.layout.addWidget(LoginPanel(), 0, 1)
self.set_background()
self.show()
#self.layout.setAlignment(PyQt5.QtCore.Qt.AlignCenter)
def set_background(self):
img = PyQt5.QtGui.QPixmap("assets\\background.png")
pixmap = img.scaled(self.width(), self.height())
self.background.setPixmap(img)
self.background.resize(self.width(), self.height())
if __name__ == "__main__":
app = PyQt5.QtWidgets.QApplication(sys.argv)
a = Auth()
sys.exit(app.exec())
Here is my current code, I just wanted some help sense while looking online I was unable to find any great examples or references.
My recommendation is not to create a new window but to set it as a child of the window, and to raise it above any other child, you must use raise_() method, also add a QGraphicsDropShadowEffect to establish the floating window effect:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class LoginPanel(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(600, 400)
self.container = QtWidgets.QWidget(self)
self.container.setStyleSheet(
"""
background-color: #CBCAB7;
border-radius: 50px;
"""
)
offset = 30
self.container.setGeometry(
self.rect().adjusted(offset, offset, -offset, -offset)
)
effect = QtWidgets.QGraphicsDropShadowEffect(
blurRadius=50, offset=QtCore.QPointF(0, 0)
)
self.container.setGraphicsEffect(effect)
lay = QtWidgets.QFormLayout(self)
lay.setContentsMargins(2 * offset, 2 * offset, 2 * offset, 2 * offset)
lay.addRow("Username:", QtWidgets.QLineEdit())
lay.addRow("Email:", QtWidgets.QLineEdit())
class Auth(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Login")
self.setFixedSize(1200, 800)
self.setWindowFlags(
QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint
)
self.setWindowIcon(QtGui.QIcon("assets\\login.ico"))
self.background = QtWidgets.QLabel(self)
self.set_background()
self.panel = LoginPanel(self)
self.center_panel()
def set_background(self):
img = QtGui.QPixmap("assets\\background.png")
pixmap = img.scaled(self.size())
self.background.setPixmap(pixmap)
self.background.resize(self.size())
def resizeEvent(self, event):
super().resizeEvent(event)
self.center_panel()
def center_panel(self):
g = self.panel.geometry()
g.moveCenter(self.rect().center())
self.panel.setGeometry(g)
self.panel.raise_()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
a = Auth()
a.show()
sys.exit(app.exec())

PyQt: How to create custom combined titlebar and menubar

I'd like to set the menu and title in one bar, but have no idea that how to layout the menu bar and title bar (or my own title bar).
# -*- coding:utf-8 -*-
from PyQt5 import QtWidgets,QtGui,QtCore
import sys
qss = ""
class UI(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setui()
def setui(self):
#----------main-window----------------------
self.setGeometry(0,0,1366,768) #x,y,w,h
self.setWindowTitle('hello world')
self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
#----------menu-bar---------------------
#--------file-menu-----
self.menu_file=self.menuBar().addMenu('file')
self.menu_file_open=self.menu_file.addAction('open')
self.menu_file_save=self.menu_file.addAction('save')
self.menu_file_saveas=self.menu_file.addAction('save as...')
self.menu_file_quit=self.menu_file.addAction('exit')
#-----------experient-menu----------
self.menu_work=self.menuBar().addMenu('work')
#-------------analysis-menu---------
self.menu_analysis=self.menuBar().addMenu('analysis')
#------------edit-menu--------------
self.menu_edit=self.menuBar().addMenu('edit')
#------------window-menu--------------
self.menu_window=self.menuBar().addMenu('window')
#------------help---menu--------------
self.menu_help=self.menuBar().addMenu('help')
#-------------set---qss----------------------
self.setStyleSheet(qss)
#-------functions--connect-------------------
self.menu_file_quit.triggered.connect(QtWidgets.qApp.quit)
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = UI()
sys.exit(app.exec_())
I expect a bar include icon, menus, title and the three buttons, just like the menu bar of vscode.
While the answer provided by #SNick is fine, I'd like to add my own proposal.
It is a bit more complex, but has some features his solution is missing and that are quite important in my opinion.
it actually uses a QMainWindow;
it can be used with ui files created in Designer. I only tried using uic.loadUi, but I think it could work with files created with pyuic too;
since it can use ui files, you can create the menu directly in designer;
being a QMainWindow, the statusBar is an actual QStatusBar;
supports the current system theme style and colors;
under Windows, it supports the window system menu;
has no size contraints, as the menu and title resize themselves according to the available space
That said, it's not perfect. So far, the only drawback I found is that it doesn't support toolbars and dockwidgets in the top area; I think it could be done, but it would be a bit more complicated.
The trick is to create a QMenuBar (or use the one set in Designer) that is not a native one, which is very important for MacOS, and add a top margin to the central widget, then use an internal QStyleOptionTitleBar to compute its size and draw its contents.
Be aware that whenever you want to add menubar items/menu, set other properties, or manually set a central widget, you must ensure that you do that after the *** END OF SETUP *** comment.
import sys
if sys.platform == 'win32':
import win32gui
import win32con
from PyQt5 import QtCore, QtGui, QtWidgets
# a "fake" button class that we need for hover and click events
class HiddenButton(QtWidgets.QPushButton):
hover = QtCore.pyqtSignal()
def __init__(self, parent):
super(HiddenButton, self).__init__(parent)
# prevent any painting to keep this button "invisible" while
# still reacting to its events
self.setUpdatesEnabled(False)
self.setFocusPolicy(QtCore.Qt.NoFocus)
def enterEvent(self, event):
self.hover.emit()
def leaveEvent(self, event):
self.hover.emit()
class SpecialTitleWindow(QtWidgets.QMainWindow):
__watchedActions = (
QtCore.QEvent.ActionAdded,
QtCore.QEvent.ActionChanged,
QtCore.QEvent.ActionRemoved
)
titleOpt = None
__menuBar = None
__titleBarMousePos = None
__sysMenuLock = False
__topMargin = 0
def __init__(self):
super(SpecialTitleWindow, self).__init__()
self.widgetHelpers = []
# uic.loadUi('titlebar.ui', self)
# enable the system menu
self.setWindowFlags(
QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint
)
# set the WindowActive to ensure that the title bar is painted as active
self.setWindowState(self.windowState() | QtCore.Qt.WindowActive)
# create a StyleOption that we need for painting and computing sizes
self.titleOpt = QtWidgets.QStyleOptionTitleBar()
self.titleOpt.initFrom(self)
self.titleOpt.titleBarFlags = (
QtCore.Qt.Window | QtCore.Qt.MSWindowsOwnDC |
QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinMaxButtonsHint |
QtCore.Qt.WindowCloseButtonHint
)
self.titleOpt.state |= (QtWidgets.QStyle.State_Active |
QtWidgets.QStyle.State_HasFocus)
self.titleOpt.titleBarState = (int(self.windowState()) |
int(QtWidgets.QStyle.State_Active))
# create "fake" buttons
self.systemButton = HiddenButton(self)
self.systemButton.pressed.connect(self.showSystemMenu)
self.minimizeButton = HiddenButton(self)
self.minimizeButton.hover.connect(self.checkHoverStates)
self.minimizeButton.clicked.connect(self.minimize)
self.maximizeButton = HiddenButton(self)
self.maximizeButton.hover.connect(self.checkHoverStates)
self.maximizeButton.clicked.connect(self.maximize)
self.closeButton = HiddenButton(self)
self.closeButton.hover.connect(self.checkHoverStates)
self.closeButton.clicked.connect(self.close)
self.ctrlButtons = {
QtWidgets.QStyle.SC_TitleBarMinButton: self.minimizeButton,
QtWidgets.QStyle.SC_TitleBarMaxButton: self.maximizeButton,
QtWidgets.QStyle.SC_TitleBarNormalButton: self.maximizeButton,
QtWidgets.QStyle.SC_TitleBarCloseButton: self.closeButton,
}
self.widgetHelpers.extend([self.minimizeButton, self.maximizeButton, self.closeButton])
self.resetTitleHeight()
# *** END OF SETUP ***
fileMenu = self.menuBar().addMenu('File')
fileMenu.addAction('Open')
fileMenu.addAction('Save')
workMenu = self.menuBar().addMenu('Work')
workMenu.addAction('Work something')
analysisMenu = self.menuBar().addMenu('Analysis')
analysisMenu.addAction('Analize action')
# just call the statusBar to create one, we use it for resizing purposes
self.statusBar()
def resetTitleHeight(self):
# minimum height for the menu can change everytime an action is added,
# removed or modified; let's update it accordingly
if not self.titleOpt:
return
# set the minimum height of the titlebar
self.titleHeight = max(
self.style().pixelMetric(
QtWidgets.QStyle.PM_TitleBarHeight, self.titleOpt, self),
self.menuBar().sizeHint().height()
)
self.titleOpt.rect.setHeight(self.titleHeight)
self.menuBar().setMaximumHeight(self.titleHeight)
if self.minimumHeight() < self.titleHeight:
self.setMinimumHeight(self.titleHeight)
def checkHoverStates(self):
if not self.titleOpt:
return
# update the window buttons when hovering
pos = self.mapFromGlobal(QtGui.QCursor.pos())
for ctrl, btn in self.ctrlButtons.items():
rect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, ctrl, self)
# since the maximize button can become a "restore", ensure that it
# actually exists according to the current state, if the rect
# has an actual size
if rect and pos in rect:
self.titleOpt.activeSubControls = ctrl
self.titleOpt.state |= QtWidgets.QStyle.State_MouseOver
break
else:
# no hover
self.titleOpt.state &= ~QtWidgets.QStyle.State_MouseOver
self.titleOpt.activeSubControls = QtWidgets.QStyle.SC_None
self.titleOpt.state |= QtWidgets.QStyle.State_Active
self.update()
def showSystemMenu(self, pos=None):
# show the system menu on windows
if sys.platform != 'win32':
return
if self.__sysMenuLock:
self.__sysMenuLock = False
return
winId = int(self.effectiveWinId())
sysMenu = win32gui.GetSystemMenu(winId, False)
if pos is None:
pos = self.systemButton.mapToGlobal(self.systemButton.rect().bottomLeft())
self.__sysMenuLock = True
cmd = win32gui.TrackPopupMenu(sysMenu,
win32gui.TPM_LEFTALIGN | win32gui.TPM_TOPALIGN | win32gui.TPM_RETURNCMD,
pos.x(), pos.y(), 0, winId, None)
win32gui.PostMessage(winId, win32con.WM_SYSCOMMAND, cmd, 0)
# restore the menu lock to hide it when clicking the system menu icon
QtCore.QTimer.singleShot(0, lambda: setattr(self, '__sysMenuLock', False))
def actualWindowTitle(self):
# window title can show "*" for modified windows
title = self.windowTitle()
if title:
title = title.replace('[*]', '*' if self.isWindowModified() else '')
return title
def updateTitleBar(self):
# compute again sizes when resizing or changing window title
menuWidth = self.menuBar().sizeHint().width()
availableRect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, QtWidgets.QStyle.SC_TitleBarLabel, self)
left = availableRect.left()
if self.menuBar().sizeHint().height() < self.titleHeight:
top = (self.titleHeight - self.menuBar().sizeHint().height()) // 2
height = self.menuBar().sizeHint().height()
else:
top = 0
height = self.titleHeight
title = self.actualWindowTitle()
titleWidth = self.fontMetrics().width(title)
if not title and menuWidth > availableRect.width():
# resize the menubar to its maximum, but without hiding the buttons
width = availableRect.width()
elif menuWidth + titleWidth > availableRect.width():
# if the menubar and title require more than the available space,
# divide it equally, giving precedence to the window title space,
# since it is also necessary for window movement
width = availableRect.width() // 2
if menuWidth > titleWidth:
width = max(left, min(availableRect.width() - titleWidth, width))
# keep a minimum size for the menu arrow
if availableRect.width() - width < left:
width = left
extButton = self.menuBar().findChild(QtWidgets.QToolButton, 'qt_menubar_ext_button')
if self.isVisible() and extButton:
# if the "extButton" is visible (meaning that some item
# is hidden due to the menubar cannot be completely shown)
# resize to the last visible item + extButton, so that
# there's as much space available for the title
minWidth = extButton.width()
menuBar = self.menuBar()
spacing = self.style().pixelMetric(QtWidgets.QStyle.PM_MenuBarItemSpacing)
for i, action in enumerate(menuBar.actions()):
actionWidth = menuBar.actionGeometry(action).width()
if minWidth + actionWidth > width:
width = minWidth
break
minWidth += actionWidth + spacing
else:
width = menuWidth
self.menuBar().setGeometry(left, top, width, height)
# ensure that our internal widget are always on top
for w in self.widgetHelpers:
w.raise_()
self.update()
# helper function to avoid "ugly" colors on menubar items
def __setMenuBar(self, menuBar):
if self.__menuBar:
if self.__menuBar in self.widgetHelpers:
self.widgetHelpers.remove(self.__menuBar)
self.__menuBar.removeEventFilter(self)
self.__menuBar = menuBar
self.widgetHelpers.append(menuBar)
self.__menuBar.installEventFilter(self)
self.__menuBar.setNativeMenuBar(False)
self.__menuBar.setStyleSheet('''
QMenuBar {
background-color: transparent;
}
QMenuBar::item {
background-color: transparent;
}
QMenuBar::item:selected {
background-color: palette(button);
}
''')
def setMenuBar(self, menuBar):
self.__setMenuBar(menuBar)
def menuBar(self):
# QMainWindow.menuBar() returns a new blank menu bar if none exists
if not self.__menuBar:
self.__setMenuBar(QtWidgets.QMenuBar(self))
return self.__menuBar
def setCentralWidget(self, widget):
if self.centralWidget():
self.centralWidget().removeEventFilter(self)
# store the top content margin, we need it later
l, self.__topMargin, r, b = widget.getContentsMargins()
super(SpecialTitleWindow, self).setCentralWidget(widget)
# since the central widget always uses all the available space and can
# capture mouse events, install an event filter to catch them and
# allow us to grab them
widget.installEventFilter(self)
def eventFilter(self, source, event):
if source == self.centralWidget():
# do not propagate mouse press events to the centralWidget!
if (event.type() == QtCore.QEvent.MouseButtonPress and
event.button() == QtCore.Qt.LeftButton and
event.y() <= self.titleHeight):
self.__titleBarMousePos = event.pos()
event.accept()
return True
elif source == self.__menuBar and event.type() in self.__watchedActions:
self.resetTitleHeight()
return super(SpecialTitleWindow, self).eventFilter(source, event)
def minimize(self):
self.setWindowState(QtCore.Qt.WindowMinimized)
def maximize(self):
if self.windowState() & QtCore.Qt.WindowMaximized:
self.setWindowState(
self.windowState() & (~QtCore.Qt.WindowMaximized | QtCore.Qt.WindowActive))
else:
self.setWindowState(
self.windowState() | QtCore.Qt.WindowMaximized | QtCore.Qt.WindowActive)
# whenever a window is resized, its button states have to be checked again
self.checkHoverStates()
def contextMenuEvent(self, event):
if event.pos() not in self.menuBar().geometry():
self.showSystemMenu(event.globalPos())
def mousePressEvent(self, event):
if not self.centralWidget() and (event.type() == QtCore.QEvent.MouseButtonPress and
event.button() == QtCore.Qt.LeftButton and event.y() <= self.titleHeight):
self.__titleBarMousePos = event.pos()
def mouseMoveEvent(self, event):
super(SpecialTitleWindow, self).mouseMoveEvent(event)
if event.buttons() == QtCore.Qt.LeftButton and self.__titleBarMousePos:
# move the window
self.move(self.pos() + event.pos() - self.__titleBarMousePos)
def mouseDoubleClickEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.maximize()
def mouseReleaseEvent(self, event):
super(SpecialTitleWindow, self).mouseReleaseEvent(event)
self.__titleBarMousePos = None
def changeEvent(self, event):
# change the appearance of the titlebar according to the window state
if event.type() == QtCore.QEvent.ActivationChange:
if self.isActiveWindow():
self.titleOpt.titleBarState = (
int(self.windowState()) | int(QtWidgets.QStyle.State_Active))
self.titleOpt.palette.setCurrentColorGroup(QtGui.QPalette.Active)
else:
self.titleOpt.titleBarState = 0
self.titleOpt.palette.setCurrentColorGroup(QtGui.QPalette.Inactive)
self.update()
elif event.type() == QtCore.QEvent.WindowStateChange:
self.checkHoverStates()
elif event.type() == QtCore.QEvent.WindowTitleChange:
if self.titleOpt:
self.updateTitleBar()
def showEvent(self, event):
if not event.spontaneous():
# update the titlebar as soon as it's shown, to ensure that
# most of the title text is visible
self.updateTitleBar()
def resizeEvent(self, event):
super(SpecialTitleWindow, self).resizeEvent(event)
# update the centralWidget contents margins, adding the titlebar height
# to the top margin found before
if (self.centralWidget() and
self.centralWidget().getContentsMargins()[1] + self.__topMargin != self.titleHeight):
l, t, r, b = self.centralWidget().getContentsMargins()
self.centralWidget().setContentsMargins(
l, self.titleHeight + self.__topMargin, r, b)
# resize the width of the titlebar option, and move its buttons
self.titleOpt.rect.setWidth(self.width())
for ctrl, btn in self.ctrlButtons.items():
rect = self.style().subControlRect(
QtWidgets.QStyle.CC_TitleBar, self.titleOpt, ctrl, self)
if rect:
btn.setGeometry(rect)
sysRect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, QtWidgets.QStyle.SC_TitleBarSysMenu, self)
if sysRect:
self.systemButton.setGeometry(sysRect)
self.titleOpt.titleBarState = int(self.windowState())
if self.isActiveWindow():
self.titleOpt.titleBarState |= int(QtWidgets.QStyle.State_Active)
self.updateTitleBar()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
self.style().drawComplexControl(QtWidgets.QStyle.CC_TitleBar, self.titleOpt, qp, self)
titleRect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, QtWidgets.QStyle.SC_TitleBarLabel, self)
icon = self.windowIcon()
if not icon.isNull():
iconRect = QtCore.QRect(0, 0, titleRect.left(), self.titleHeight)
qp.drawPixmap(iconRect, icon.pixmap(iconRect.size()))
title = self.actualWindowTitle()
titleRect.setLeft(self.menuBar().geometry().right())
if title:
# move left of the rectangle available for the title to the right of
# the menubar; if the title is bigger than the available space, elide it
elided = self.fontMetrics().elidedText(
title, QtCore.Qt.ElideRight, titleRect.width() - 2)
qp.drawText(titleRect, QtCore.Qt.AlignCenter, elided)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = SpecialTitleWindow()
w.setWindowTitle('My window')
w.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5.QtCore import pyqtSlot, QPoint, Qt, QRect
from PyQt5.QtWidgets import (QMainWindow, QApplication, QPushButton, QHBoxLayout,
QVBoxLayout, QTabWidget, QWidget, QAction,
QLabel, QSizeGrip, QMenuBar, qApp)
from PyQt5.QtGui import QIcon
class TitleBar(QWidget):
height = 35
def __init__(self, parent):
super(TitleBar, self).__init__()
self.parent = parent
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.menu_bar = QMenuBar()
self.menu_bar.setStyleSheet("""
color: #fff;
background-color: #23272A;
font-size: 14px;
padding: 4px;
""")
self.menu_file = self.menu_bar.addMenu('file')
self.menu_file_open=self.menu_file.addAction('open')
self.menu_file_save=self.menu_file.addAction('save')
self.menu_file_saveas=self.menu_file.addAction('save as...')
self.menu_file_quit=self.menu_file.addAction('exit')
self.menu_file_quit.triggered.connect(qApp.quit)
self.menu_work=self.menu_bar.addMenu('work')
self.menu_analysis=self.menu_bar.addMenu('analysis')
self.menu_edit=self.menu_bar.addMenu('edit')
self.menu_window=self.menu_bar.addMenu('window')
self.menu_help=self.menu_bar.addMenu('help')
self.layout.addWidget(self.menu_bar)
self.title = QLabel("Hello World!")
self.title.setFixedHeight(self.height)
self.layout.addWidget(self.title)
self.title.setStyleSheet("""
background-color: #23272a; /* 23272a #f00*/
font-weight: bold;
font-size: 16px;
color: blue;
padding-left: 170px;
""")
self.closeButton = QPushButton(' ')
self.closeButton.clicked.connect(self.on_click_close)
self.closeButton.setStyleSheet("""
background-color: #DC143C;
border-radius: 10px;
height: {};
width: {};
margin-right: 3px;
font-weight: bold;
color: #000;
font-family: "Webdings";
qproperty-text: "r";
""".format(self.height/1.7,self.height/1.7))
self.maxButton = QPushButton(' ')
self.maxButton.clicked.connect(self.on_click_maximize)
self.maxButton.setStyleSheet("""
background-color: #32CD32;
border-radius: 10px;
height: {};
width: {};
margin-right: 3px;
font-weight: bold;
color: #000;
font-family: "Webdings";
qproperty-text: "1";
""".format(self.height/1.7,self.height/1.7))
self.hideButton = QPushButton(' ')
self.hideButton.clicked.connect(self.on_click_hide)
self.hideButton.setStyleSheet("""
background-color: #FFFF00;
border-radius: 10px;
height: {};
width: {};
margin-right: 3px;
font-weight: bold;
color: #000;
font-family: "Webdings";
qproperty-text: "0";
""".format(self.height/1.7,self.height/1.7))
self.layout.addWidget(self.hideButton)
self.layout.addWidget(self.maxButton)
self.layout.addWidget(self.closeButton)
self.setLayout(self.layout)
self.start = QPoint(0, 0)
self.pressing = False
self.maximaze = False
def resizeEvent(self, QResizeEvent):
super(TitleBar, 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.move(self.mapToGlobal(self.movement))
self.start = self.end
def mouseReleaseEvent(self, QMouseEvent):
self.pressing = False
def on_click_close(self):
sys.exit()
def on_click_maximize(self):
self.maximaze = not self.maximaze
if self.maximaze: self.parent.setWindowState(Qt.WindowNoState)
if not self.maximaze:
self.parent.setWindowState(Qt.WindowMaximized)
def on_click_hide(self):
self.parent.showMinimized()
class StatusBar(QWidget):
def __init__(self, parent):
super(StatusBar, self).__init__()
self.initUI()
self.showMessage("showMessage: Hello world!")
def initUI(self):
self.label = QLabel("Status bar...")
self.label.setFixedHeight(24)
self.label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.label.setStyleSheet("""
background-color: #23272a;
font-size: 12px;
padding-left: 5px;
color: white;
""")
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.layout.addWidget(self.label)
self.setLayout(self.layout)
def showMessage(self, text):
self.label.setText(text)
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setFixedSize(800, 400)
self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
self.setStyleSheet("background-color: #2c2f33;")
self.setWindowTitle('Code Maker')
self.title_bar = TitleBar(self)
self.status_bar = StatusBar(self)
self.layout = QVBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.layout.addWidget(self.title_bar)
self.layout.addStretch(1)
self.layout.addWidget(self.status_bar)
self.layout.setSpacing(0)
self.setLayout(self.layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
I did a few patches so that the code provided by #musicamante can work on PySide6, but I found that when moving the window, it's shaking. When I looked at the mouseMoveEvent and read qt's document about event.pos() in QMouseEvent, which says:
If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion.
So I replaced
self.move(self.pos() + event.pos() - self.__titleBarMousePos)
with
self.move(event.globalPos() - self.__titleBarMousePos)
in mouseMoveEvent()
Here is the PySide6 version:
import sys
if sys.platform == 'win32':
import win32gui
import win32con
from PySide6 import QtCore, QtGui, QtWidgets
# a "fake" button class that we need for hover and click events
class HiddenButton(QtWidgets.QPushButton):
hover = QtCore.Signal()
def __init__(self, parent):
super(HiddenButton, self).__init__(parent)
# prevent any painting to keep this button "invisible" while
# still reacting to its events
self.setUpdatesEnabled(False)
self.setFocusPolicy(QtCore.Qt.NoFocus)
def enterEvent(self, event):
self.hover.emit()
def leaveEvent(self, event):
self.hover.emit()
class SpecialTitleWindow(QtWidgets.QMainWindow):
__watchedActions = (
QtCore.QEvent.ActionAdded,
QtCore.QEvent.ActionChanged,
QtCore.QEvent.ActionRemoved
)
titleOpt = None
__menuBar = None
__titleBarMousePos = None
__sysMenuLock = False
__topMargin = 0
def __init__(self):
super(SpecialTitleWindow, self).__init__()
self.widgetHelpers = []
# uic.loadUi('titlebar.ui', self)
# enable the system menu
self.setWindowFlags(
QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint
)
# set the WindowActive to ensure that the title bar is painted as active
self.setWindowState(self.windowState() | QtCore.Qt.WindowActive)
# create a StyleOption that we need for painting and computing sizes
self.titleOpt = QtWidgets.QStyleOptionTitleBar()
self.titleOpt.initFrom(self)
self.titleOpt.titleBarFlags = (
QtCore.Qt.Window | QtCore.Qt.MSWindowsOwnDC |
QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMinMaxButtonsHint |
QtCore.Qt.WindowCloseButtonHint
)
self.titleOpt.state |= (QtWidgets.QStyle.State_Active |
QtWidgets.QStyle.State_HasFocus)
self.titleOpt.titleBarState = (int(self.windowState()) |
int(QtWidgets.QStyle.State_Active))
# create "fake" buttons
self.systemButton = HiddenButton(self)
self.systemButton.pressed.connect(self.showSystemMenu)
self.minimizeButton = HiddenButton(self)
self.minimizeButton.hover.connect(self.checkHoverStates)
self.minimizeButton.clicked.connect(self.minimize)
self.maximizeButton = HiddenButton(self)
self.maximizeButton.hover.connect(self.checkHoverStates)
self.maximizeButton.clicked.connect(self.maximize)
self.closeButton = HiddenButton(self)
self.closeButton.hover.connect(self.checkHoverStates)
self.closeButton.clicked.connect(self.close)
self.ctrlButtons = {
QtWidgets.QStyle.SC_TitleBarMinButton: self.minimizeButton,
QtWidgets.QStyle.SC_TitleBarMaxButton: self.maximizeButton,
QtWidgets.QStyle.SC_TitleBarNormalButton: self.maximizeButton,
QtWidgets.QStyle.SC_TitleBarCloseButton: self.closeButton,
}
self.widgetHelpers.extend([self.minimizeButton, self.maximizeButton, self.closeButton])
self.resetTitleHeight()
# *** END OF SETUP ***
fileMenu = self.menuBar().addMenu('File')
fileMenu.addAction('Open')
fileMenu.addAction('Save')
workMenu = self.menuBar().addMenu('Work')
workMenu.addAction('Work something')
analysisMenu = self.menuBar().addMenu('Analysis')
analysisMenu.addAction('Analize action')
# just call the statusBar to create one, we use it for resizing purposes
self.statusBar()
self.resize(400, 250)
def resetTitleHeight(self):
# minimum height for the menu can change everytime an action is added,
# removed or modified; let's update it accordingly
if not self.titleOpt:
return
# set the minimum height of the titlebar
self.titleHeight = max(
self.style().pixelMetric(
QtWidgets.QStyle.PM_TitleBarHeight, self.titleOpt, self),
self.menuBar().sizeHint().height()
)
self.titleOpt.rect.setHeight(self.titleHeight)
self.menuBar().setMaximumHeight(self.titleHeight)
if self.minimumHeight() < self.titleHeight:
self.setMinimumHeight(self.titleHeight)
def checkHoverStates(self):
if not self.titleOpt:
return
# update the window buttons when hovering
pos = self.mapFromGlobal(QtGui.QCursor.pos())
for ctrl, btn in self.ctrlButtons.items():
rect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, ctrl, self)
# since the maximize button can become a "restore", ensure that it
# actually exists according to the current state, if the rect
# has an actual size
if rect and rect.contains(pos):
self.titleOpt.activeSubControls = ctrl
self.titleOpt.state |= QtWidgets.QStyle.State_MouseOver
break
else:
# no hover
self.titleOpt.state &= ~QtWidgets.QStyle.State_MouseOver
self.titleOpt.activeSubControls = QtWidgets.QStyle.SC_None
self.titleOpt.state |= QtWidgets.QStyle.State_Active
self.update()
def showSystemMenu(self, pos=None):
# show the system menu on windows
if sys.platform != 'win32':
return
if self.__sysMenuLock:
self.__sysMenuLock = False
return
winId = int(self.effectiveWinId())
sysMenu = win32gui.GetSystemMenu(winId, False)
if pos is None:
pos = self.systemButton.mapToGlobal(self.systemButton.rect().bottomLeft())
self.__sysMenuLock = True
cmd = win32gui.TrackPopupMenu(sysMenu,
win32gui.TPM_LEFTALIGN | win32gui.TPM_TOPALIGN | win32gui.TPM_RETURNCMD,
pos.x(), pos.y(), 0, winId, None)
win32gui.PostMessage(winId, win32con.WM_SYSCOMMAND, cmd, 0)
# restore the menu lock to hide it when clicking the system menu icon
QtCore.QTimer.singleShot(0, lambda: setattr(self, '__sysMenuLock', False))
def actualWindowTitle(self):
# window title can show "*" for modified windows
title = self.windowTitle()
if title:
title = title.replace('[*]', '*' if self.isWindowModified() else '')
return title
def updateTitleBar(self):
# compute again sizes when resizing or changing window title
menuWidth = self.menuBar().sizeHint().width()
availableRect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, QtWidgets.QStyle.SC_TitleBarLabel, self)
left = availableRect.left()
if self.menuBar().sizeHint().height() < self.titleHeight:
top = (self.titleHeight - self.menuBar().sizeHint().height()) // 2
height = self.menuBar().sizeHint().height()
else:
top = 0
height = self.titleHeight
title = self.actualWindowTitle()
titleWidth = self.fontMetrics().boundingRect(title).width()
if not title and menuWidth > availableRect.width():
# resize the menubar to its maximum, but without hiding the buttons
width = availableRect.width()
elif menuWidth + titleWidth > availableRect.width():
# if the menubar and title require more than the available space,
# divide it equally, giving precedence to the window title space,
# since it is also necessary for window movement
width = availableRect.width() // 2
if menuWidth > titleWidth:
width = max(left, min(availableRect.width() - titleWidth, width))
# keep a minimum size for the menu arrow
if availableRect.width() - width < left:
width = left
extButton = self.menuBar().findChild(QtWidgets.QToolButton, 'qt_menubar_ext_button')
if self.isVisible() and extButton:
# if the "extButton" is visible (meaning that some item
# is hidden due to the menubar cannot be completely shown)
# resize to the last visible item + extButton, so that
# there's as much space available for the title
minWidth = extButton.width()
menuBar = self.menuBar()
spacing = self.style().pixelMetric(QtWidgets.QStyle.PM_MenuBarItemSpacing)
for i, action in enumerate(menuBar.actions()):
actionWidth = menuBar.actionGeometry(action).width()
if minWidth + actionWidth > width:
width = minWidth
break
minWidth += actionWidth + spacing
else:
width = menuWidth
self.menuBar().setGeometry(left, top, width, height)
# ensure that our internal widget are always on top
for w in self.widgetHelpers:
w.raise_()
self.update()
# helper function to avoid "ugly" colors on menubar items
def __setMenuBar(self, menuBar):
if self.__menuBar:
if self.__menuBar in self.widgetHelpers:
self.widgetHelpers.remove(self.__menuBar)
self.__menuBar.removeEventFilter(self)
self.__menuBar = menuBar
self.widgetHelpers.append(menuBar)
self.__menuBar.installEventFilter(self)
self.__menuBar.setNativeMenuBar(False)
self.__menuBar.setStyleSheet('''
QMenuBar {
background-color: transparent;
}
QMenuBar::item {
background-color: transparent;
}
QMenuBar::item:selected {
background-color: palette(button);
}
''')
def setMenuBar(self, menuBar):
self.__setMenuBar(menuBar)
def menuBar(self):
# QMainWindow.menuBar() returns a new blank menu bar if none exists
if not self.__menuBar:
self.__setMenuBar(QtWidgets.QMenuBar(self))
return self.__menuBar
def setCentralWidget(self, widget):
if self.centralWidget():
self.centralWidget().removeEventFilter(self)
# store the top content margin, we need it later
l, self.__topMargin, r, b = widget.contentsMargins()
super(SpecialTitleWindow, self).setCentralWidget(widget)
# since the central widget always uses all the available space and can
# capture mouse events, install an event filter to catch them and
# allow us to grab them
widget.installEventFilter(self)
def eventFilter(self, source, event):
if source == self.centralWidget():
# do not propagate mouse press events to the centralWidget!
if (event.type() == QtCore.QEvent.MouseButtonPress and
event.button() == QtCore.Qt.LeftButton and
event.y() <= self.titleHeight):
self.__titleBarMousePos = event.pos()
event.accept()
return True
elif source == self.__menuBar and event.type() in self.__watchedActions:
self.resetTitleHeight()
return super(SpecialTitleWindow, self).eventFilter(source, event)
def minimize(self):
self.setWindowState(QtCore.Qt.WindowMinimized)
def maximize(self):
if self.windowState() & QtCore.Qt.WindowMaximized:
self.setWindowState(
self.windowState() & (~QtCore.Qt.WindowMaximized | QtCore.Qt.WindowActive))
else:
self.setWindowState(
self.windowState() | QtCore.Qt.WindowMaximized | QtCore.Qt.WindowActive)
# whenever a window is resized, its button states have to be checked again
self.checkHoverStates()
def contextMenuEvent(self, event):
if not self.menuBar().geometry().contains(event.pos()):
self.showSystemMenu(event.globalPos())
def mousePressEvent(self, event):
if not self.centralWidget() and (event.type() == QtCore.QEvent.MouseButtonPress and
event.button() == QtCore.Qt.LeftButton and event.position().y() <= self.titleHeight):
self.__titleBarMousePos = event.position()
def mouseMoveEvent(self, event):
super(SpecialTitleWindow, self).mouseMoveEvent(event)
if event.buttons() == QtCore.Qt.LeftButton and self.__titleBarMousePos:
# move the window
self.move((event.globalPosition() - self.__titleBarMousePos).toPoint())
def mouseDoubleClickEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.maximize()
def mouseReleaseEvent(self, event):
super(SpecialTitleWindow, self).mouseReleaseEvent(event)
self.__titleBarMousePos = None
def changeEvent(self, event):
# change the appearance of the titlebar according to the window state
if event.type() == QtCore.QEvent.ActivationChange:
if self.isActiveWindow():
self.titleOpt.titleBarState = (
int(self.windowState()) | int(QtWidgets.QStyle.State_Active))
self.titleOpt.palette.setCurrentColorGroup(QtGui.QPalette.Active)
else:
self.titleOpt.titleBarState = 0
self.titleOpt.palette.setCurrentColorGroup(QtGui.QPalette.Inactive)
self.update()
elif event.type() == QtCore.QEvent.WindowStateChange:
self.checkHoverStates()
elif event.type() == QtCore.QEvent.WindowTitleChange:
if self.titleOpt:
self.updateTitleBar()
def showEvent(self, event):
if not event.spontaneous():
# update the titlebar as soon as it's shown, to ensure that
# most of the title text is visible
self.updateTitleBar()
def resizeEvent(self, event):
super(SpecialTitleWindow, self).resizeEvent(event)
# update the centralWidget contents margins, adding the titlebar height
# to the top margin found before
if (self.centralWidget() and
self.centralWidget().getContentsMargins()[1] + self.__topMargin != self.titleHeight):
l, t, r, b = self.centralWidget().getContentsMargins()
self.centralWidget().setContentsMargins(
l, self.titleHeight + self.__topMargin, r, b)
# resize the width of the titlebar option, and move its buttons
self.titleOpt.rect.setWidth(self.width())
for ctrl, btn in self.ctrlButtons.items():
rect = self.style().subControlRect(
QtWidgets.QStyle.CC_TitleBar, self.titleOpt, ctrl, self)
if rect:
btn.setGeometry(rect)
sysRect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, QtWidgets.QStyle.SC_TitleBarSysMenu, self)
if sysRect:
self.systemButton.setGeometry(sysRect)
self.titleOpt.titleBarState = int(self.windowState())
if self.isActiveWindow():
self.titleOpt.titleBarState |= int(QtWidgets.QStyle.State_Active)
self.updateTitleBar()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
self.style().drawComplexControl(QtWidgets.QStyle.CC_TitleBar, self.titleOpt, qp, self)
titleRect = self.style().subControlRect(QtWidgets.QStyle.CC_TitleBar,
self.titleOpt, QtWidgets.QStyle.SC_TitleBarLabel, self)
icon = self.windowIcon()
if not icon.isNull():
iconRect = QtCore.QRect(0, 0, titleRect.left(), self.titleHeight)
qp.drawPixmap(iconRect, icon.pixmap(iconRect.size()))
title = self.actualWindowTitle()
titleRect.setLeft(self.menuBar().geometry().right())
if title:
# move left of the rectangle available for the title to the right of
# the menubar; if the title is bigger than the available space, elide it
elided = self.fontMetrics().elidedText(
title, QtCore.Qt.ElideRight, titleRect.width() - 2)
qp.drawText(titleRect, QtCore.Qt.AlignCenter, elided)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = SpecialTitleWindow()
w.setWindowTitle('My window')
w.show()
sys.exit(app.exec())

Custom Titlebar with frame in PyQt5

I'm working on an opensource markdown supported minimal note taking application for Windows/Linux. I'm trying to remove the title bar and add my own buttons. I want something like, a title bar with only two custom buttons as shown in the figure
Currently I have this:
I've tried modifying the window flags:
With not window flags, the window is both re-sizable and movable. But no custom buttons.
Using self.setWindowFlags(QtCore.Qt.FramelessWindowHint), the window has no borders, but cant move or resize the window
Using self.setWindowFlags(QtCore.Qt.CustomizeWindowHint), the window is resizable but cannot move and also cant get rid of the white part at the top of the window.
Any help appreciated. You can find the project on GitHub here.
Thanks..
This is my python code:
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, uic
import sys
import os
import markdown2 # https://github.com/trentm/python-markdown2
from PyQt5.QtCore import QRect
from PyQt5.QtGui import QFont
simpleUiForm = uic.loadUiType("Simple.ui")[0]
class SimpleWindow(QtWidgets.QMainWindow, simpleUiForm):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.markdown = markdown2.Markdown()
self.css = open(os.path.join("css", "default.css")).read()
self.editNote.setPlainText("")
#self.noteView = QtWebEngineWidgets.QWebEngineView(self)
self.installEventFilter(self)
self.displayNote.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
#self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
def eventFilter(self, object, event):
if event.type() == QtCore.QEvent.WindowActivate:
print("widget window has gained focus")
self.editNote.show()
self.displayNote.hide()
elif event.type() == QtCore.QEvent.WindowDeactivate:
print("widget window has lost focus")
note = self.editNote.toPlainText()
htmlNote = self.getStyledPage(note)
# print(note)
self.editNote.hide()
self.displayNote.show()
# print(htmlNote)
self.displayNote.setHtml(htmlNote)
elif event.type() == QtCore.QEvent.FocusIn:
print("widget has gained keyboard focus")
elif event.type() == QtCore.QEvent.FocusOut:
print("widget has lost keyboard focus")
return False
The UI file is created in the following hierarchy
Here are the steps you just gotta follow:
Have your MainWindow, be it a QMainWindow, or QWidget, or whatever [widget] you want to inherit.
Set its flag, self.setWindowFlags(Qt.FramelessWindowHint)
Implement your own moving around.
Implement your own buttons (close, max, min)
Implement your own resize.
Here is a small example with move around, and buttons implemented. You should still have to implement the resize using the same logic.
import sys
from PyQt5.QtCore import QPoint
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import 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_())
Here are some tips:
Option 1:
Have a QGridLayout with widget in each corner and side(e.g. left, top-left, menubar, top-right, right, bottom-right, bottom and bottom left)
With the approach (1) you would know when you are clicking in each border, you just got to define each one size and add each one on their place.
When you click on each one treat them in their respective ways, for example, if you click in the left one and drag to the left, you gotta resize it larger and at the same time move it to the left so it will appear to be stopped at the right place and grow width.
Apply this reasoning to each edge, each one behaving in the way it has to.
Option 2:
Instead of having a QGridLayout you can detect in which place you are clicking by the click pos.
Verify if the x of the click is smaller than the x of the moving pos to know if it's moving left or right and where it's being clicked.
The calculation is made in the same way of the Option1
Option 3:
Probably there are other ways, but those are the ones I just thought of. For example using the CustomizeWindowHint you said you are able to resize, so you just would have to implement what I gave you as example. BEAUTIFUL!
Tips:
Be careful with the localPos(inside own widget), globalPos(related to your screen). For example: If you click in the very left of your left widget its 'x' will be zero, if you click in the very left of the middle(content)it will be also zero, although if you mapToGlobal you will having different values according to the pos of the screen.
Pay attention when resizing, or moving, when you have to add width or subtract, or just move, or both, I'd recommend you to draw on a paper and figure out how the logic of resizing works before implementing it out of blue.
GOOD LUCK :D
While the accepted answer can be considered valid, it has some issues.
using setGeometry() is not appropriate (and the reason for using it was wrong) since it doesn't consider possible frame margins set by the style;
the position computation is unnecessarily complex;
resizing the title bar to the total width is wrong, since it doesn't consider the buttons and can also cause recursion problems in certain situations (like not setting the minimum size of the main window); also, if the title is too big, it makes impossible to resize the main window;
buttons should not accept focus;
setting a layout creates a restraint for the "main widget" or layout, so the title should not be added, but the contents margins of the widget should be used instead;
I revised the code to provide a better base for the main window, simplify the moving code, and add other features like the Qt windowTitle() property support, standard QStyle icons for buttons (instead of text), and proper maximize/normal button icons. Note that the title label is not added to the layout.
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
self.titleBar = MyBar(self)
self.setContentsMargins(0, self.titleBar.height(), 0, 0)
self.resize(640, self.titleBar.height() + 480)
def changeEvent(self, event):
if event.type() == event.WindowStateChange:
self.titleBar.windowStateChanged(self.windowState())
def resizeEvent(self, event):
self.titleBar.resize(self.width(), self.titleBar.height())
class MyBar(QWidget):
clickPos = None
def __init__(self, parent):
super(MyBar, self).__init__(parent)
self.setAutoFillBackground(True)
self.setBackgroundRole(QPalette.Shadow)
# alternatively:
# palette = self.palette()
# palette.setColor(palette.Window, Qt.black)
# palette.setColor(palette.WindowText, Qt.white)
# self.setPalette(palette)
layout = QHBoxLayout(self)
layout.setContentsMargins(1, 1, 1, 1)
layout.addStretch()
self.title = QLabel("My Own Bar", self, alignment=Qt.AlignCenter)
# if setPalette() was used above, this is not required
self.title.setForegroundRole(QPalette.Light)
style = self.style()
ref_size = self.fontMetrics().height()
ref_size += style.pixelMetric(style.PM_ButtonMargin) * 2
self.setMaximumHeight(ref_size + 2)
btn_size = QSize(ref_size, ref_size)
for target in ('min', 'normal', 'max', 'close'):
btn = QToolButton(self, focusPolicy=Qt.NoFocus)
layout.addWidget(btn)
btn.setFixedSize(btn_size)
iconType = getattr(style,
'SP_TitleBar{}Button'.format(target.capitalize()))
btn.setIcon(style.standardIcon(iconType))
if target == 'close':
colorNormal = 'red'
colorHover = 'orangered'
else:
colorNormal = 'palette(mid)'
colorHover = 'palette(light)'
btn.setStyleSheet('''
QToolButton {{
background-color: {};
}}
QToolButton:hover {{
background-color: {}
}}
'''.format(colorNormal, colorHover))
signal = getattr(self, target + 'Clicked')
btn.clicked.connect(signal)
setattr(self, target + 'Button', btn)
self.normalButton.hide()
self.updateTitle(parent.windowTitle())
parent.windowTitleChanged.connect(self.updateTitle)
def updateTitle(self, title=None):
if title is None:
title = self.window().windowTitle()
width = self.title.width()
width -= self.style().pixelMetric(QStyle.PM_LayoutHorizontalSpacing) * 2
self.title.setText(self.fontMetrics().elidedText(
title, Qt.ElideRight, width))
def windowStateChanged(self, state):
self.normalButton.setVisible(state == Qt.WindowMaximized)
self.maxButton.setVisible(state != Qt.WindowMaximized)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.clickPos = event.windowPos().toPoint()
def mouseMoveEvent(self, event):
if self.clickPos is not None:
self.window().move(event.globalPos() - self.clickPos)
def mouseReleaseEvent(self, QMouseEvent):
self.clickPos = None
def closeClicked(self):
self.window().close()
def maxClicked(self):
self.window().showMaximized()
def normalClicked(self):
self.window().showNormal()
def minClicked(self):
self.window().showMinimized()
def resizeEvent(self, event):
self.title.resize(self.minButton.x(), self.height())
self.updateTitle()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
layout = QVBoxLayout(mw)
widget = QTextEdit()
layout.addWidget(widget)
mw.show()
mw.setWindowTitle('My custom window with a very, very long title')
sys.exit(app.exec_())
This is for the people who are going to implement custom title bar in PyQt6 or PySide6
The below changes should be done in the answer given by #musicamante
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
# self.clickPos = event.windowPos().toPoint()
self.clickPos = event.scenePosition().toPoint()
def mouseMoveEvent(self, event):
if self.clickPos is not None:
# self.window().move(event.globalPos() - self.clickPos)
self.window().move(event.globalPosition().toPoint() - self.clickPos)
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
# sys.exit(app.exec_())
sys.exit(app.exec())
References:
QMouseEvent.globalPosition(),
QMouseEvent.scenePosition()
This method of moving Windows with Custom Widget doesn't work with WAYLAND. If anybody has a solution for that please post it here for future reference
Working functions for WAYLAND and PyQT6/PySide6 :
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self._move()
return super().mousePressEvent(event)
def _move(self):
window = self.window().windowHandle()
window.startSystemMove()
Please check.

Categories