PySide6 app crashes when using QPainter.drawLine() - python

On Windows 10, python3.10, PySide6 (or PyQt6) QApplication crashes when calling QPainter.drawLine() .
The terminal just displays :
Process finished with exit code -1073741819 (0xC0000005)
Please find below the code:
import sys
from PySide6.QtCore import QPoint, Qt
from PySide6.QtGui import QColor, QPainter, QPen, QPixmap
from PySide6.QtWidgets import QApplication, QLabel, QMainWindow
# from PyQt6.QtCore import QPoint, Qt
# from PyQt6.QtGui import QColor, QPainter, QPen, QPixmap
# from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.label = QLabel()
canvas = QPixmap(400, 300)
canvas.fill(Qt.GlobalColor.white)
self.label.setPixmap(canvas)
self.setCentralWidget(self.label)
self.draw_something()
def draw_something(self):
painter = QPainter(self.label.pixmap())
painter.drawLine(10, 10, 300, 200) # >=========== Crash Here
painter.end()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

This is caused by a slight (and not well documented) change in the API that happened starting with Qt5.15.
Until Qt5, pixmap() returned a direct pointer to the current pixmap of the label, while in Qt6 it returns an implicit copy of the pixmap. The difference is highlighted only for the latest Qt5 documentation of the pixmap() property:
Previously, Qt provided a version of pixmap() which returned the pixmap by-pointer. That version is now deprecated. To maintain compatibility with old code, you can explicitly differentiate between the by-pointer function and the by-value function:
To Python developers that's not obvious, but to C++ it's clear by the change of the const QPixmap * (note the asterisk, meaning that it's a pointer) to a pure QPixmap type, meaning that the returned object is a new QPixmap object based on the current pixmap, and not a reference to the pixmap object currently set for the label.
Now, the fact is that, conceptually speaking, we should not be able to directly "live draw" on the current pixmap of the label, because:
setPixmap() always creates a copy of the pixmap for the label;
due to the point above, there is no point in sharing the same pixmap object among different labels, so, as a consequence, pixmap() should always return a copy of that object;
Previously, it was possible to directly paint on a QLabel's pixmap (while ensuring that update() was immediately called on the label). The current API instead requests an explicit call to setPixmap() after drawing.
So, the solution is to create a reference to the pixmap as long as it's needed:
def draw_something(self):
pm = self.label.pixmap()
painter = QPainter(pm)
painter.drawLine(10, 10, 300, 200)
painter.end()
self.label.setPixmap(pm)

Related

How can I apply blur effect only on the background of my mainwindow?

what i want to achieve
I am learning how to use pyqt5 with this project of mine.
I tried downloading something called BlurWindow but it kept giving me a parameter error so switched back to trying to use QGraphicBlurEffect but it blurs everything inside my MainWindow
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys
from PyQt5.uic import loadUi
from BlurWindow.blurWindow import blur
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
loadUi(r'D:\Workspace\Qt Designer\blur bg\blurtest.ui',self)
self.setAttribute(Qt.WA_TranslucentBackground)
hWnd = self.winId()
print(hWnd)
blur(hWnd)
self.setStyleSheet("background-color: rgba(0, 0, 0, 0)")
app=QApplication(sys.argv)
mainwindow=MainWindow()
widget=QtWidgets.QStackedWidget()
widget.setWindowOpacity(0.5)
widget.addWidget(mainwindow)
widget.setFixedHeight(600)
widget.setFixedWidth(800)
widget.show()
sys.exit(app.exec_())
BlurWindow uses system features to set the background of a top level window.
Your problem is that you're applying it to the wrong widget, which is a child widget, not a top level one. The top level has no "glass effect" set, so the result is that it won't have any effect applied on it.
The solution is simple: apply the effect to the top level window.
import sys
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
from BlurWindow.blurWindow import blur
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
loadUi(r'D:\Workspace\Qt Designer\blur bg\blurtest.ui', self)
self.setStyleSheet("""
MainWindow {
background-color: rgba(0, 0, 0, 0);
}
""")
app = QApplication(sys.argv)
mainwindow = MainWindow()
widget = QtWidgets.QStackedWidget()
widget.addWidget(mainwindow)
widget.setFixedHeight(600)
widget.setFixedWidth(800)
blur(widget.winId()) # <---
widget.show()
sys.exit(app.exec_())
Note that:
QMainWindow is not supposed to be used as a child widget. You should switch to a basic QWidget (or other container widgets like QFrame), meaning that you should create a new "widget" in Designer and copy/paste the content of your previous window to it, otherwise loadUi() will throw an exception;
you should never apply generic style sheet properties to parent widgets, as you would get unexpected results (especially with complex widgets, like scroll areas); you should always use proper selectors (as I did above);

Using Custom Widgets in Qt Designer for PySide6 MDI application

I refer to the PySide MDI example in PySide project repository at https://github.com/pyside/Examples/blob/master/examples/mainwindows/mdi/mdi.py. I tried to adopt the same to PySide6 after changing the import reference to from PySide to PySide6. It is working fine in current form.
After making sure that the example works with PySide6, I made following additions:
Implemented a new Widget in Qt Designer (using exe installed in project VE using pip install pyside6) with just one QTextEdit widget on this form. The python code generated by designer is as below:
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'FormWidget01uyjQCJ.ui'
##
## Created by: Qt User Interface Compiler version 6.4.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QSizePolicy, QTextEdit, QWidget)
class Ui_FormWidget01(object):
def setupUi(self, FormWidget01):
if not FormWidget01.objectName():
FormWidget01.setObjectName(u"FormWidget01")
FormWidget01.resize(700, 500)
self.textEdit = QTextEdit(FormWidget01)
self.textEdit.setObjectName(u"textEdit")
self.textEdit.setGeometry(QRect(10, 10, 681, 481))
self.retranslateUi(FormWidget01)
QMetaObject.connectSlotsByName(FormWidget01)
# setupUi
def retranslateUi(self, FormWidget01):
FormWidget01.setWindowTitle(QCoreApplication.translate("FormWidget01", u"Form Widget", None))
# retranslateUi
In the mdi.py application, I added the following class for newly generated child on pattern of class MdiChild(QTestEdit) in the above example:
class FormWidget01(Ui_FormWidget01):
def __init__(self):
super(FormWidget01, self).__init__()
self.setAttribute(Qt.WA_DeleteOnClose)
self.isUntitled = True
Finally, I updated class MainWindow(QMainWindow) as below:
Added new function on pattern of newfile(self):
def newFw01(self):
_fw01 = self.createFormWidget01()
_fw01.show()
Added new function on pattern of createMdiChild(self):
def createFormWidget01(self):
fw01 = FormWidget01()
fw01.resize(400, 300)
self.mdiArea.addSubWindow(fw01)
return fw01
And updated createActions(self):
self.newFw01Act = QAction(QIcon(':/images/new.png'), "&New FW01", self,
shortcut=QKeySequence.New, statusTip="Create a new FW",
triggered=self.newFw01)
When I run the updated program and click action for new widget, I get the following error:
File "S:\***\newmdi\mdiapp.py", line 61, in __init__
self.setAttribute(Qt.WA_DeleteOnClose)
AttributeError: 'FormWidget01' object has no attribute 'setAttribute'
At this point, I realized that C++ code generated by the Designer initiate form is like this:
class Ui_FormWidget01
{
public:
QTextEdit *textEdit;
void setupUi(QWidget *FormWidget01)
{
if (FormWidget01->objectName().isEmpty())
FormWidget01->setObjectName("FormWidget01");
FormWidget01->resize(700, 500);
textEdit = new QTextEdit(FormWidget01);
textEdit->setObjectName("textEdit");
...
If I change the python UI class from class Ui_FormWidget01(object): to class Ui_FormWidget01(QWidget):, replacing object with QWidget, the action works but produces a minimized and blank instance of Ui_FormWidget01. There is no QTextEdit visible on it.
I'm not pro at coding and not sure what is going wrong.
In partcular, I need to understand if:
It is possible to create a custom Widget in Qt Designer and use it as MdiChild in Qt MDI application Framework?
If a child widget initialized with QTextEdit works as MDI child but not a child with initialized with object, what could be restrictions on type of an MDI child?
Any clue or explanation is welcome.

Embed widgets into QWindow

Basically I want to create a window using QtGui.QWindow() instead of QtWidgets.QMainWindow().
I want to do this because I want to have access to QWindow functions such as:
startSystemMove()
setTitle()
setWindowStates()
startSystemResize()
At first I thought you make the window class inherit QtGui.QWindow, but if you do that, it just creates an empty window.
However, QWindow functions do work. So my guess is that I have to somehow input the QMainWindow (or the widgets inside it) into the QWindow, but I have no idea how.
So that there is an XY problem since the objective is to modify properties of the QWindow associated with the QWidget but instead it asks how to embed a QWidget into a QWindow.
QWidget creates a QWindow after using the show() method and it can be accessed using the windowHandle() method.
import sys
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow
def main():
app = QApplication(sys.argv)
mainwindow = QMainWindow()
mainwindow.show()
window = mainwindow.windowHandle()
window.setTitle("Foo")
def start_resize():
window.startSystemResize(Qt.TopEdge)
def start_move():
window.startSystemMove()
def maximized():
window.setWindowStates(Qt.WindowMaximized)
QTimer.singleShot(5 * 1000, start_resize)
QTimer.singleShot(10 * 1000, start_move)
QTimer.singleShot(15 * 1000, maximized)
sys.exit(app.exec())
if __name__ == "__main__":
main()
Note: Some methods of the QWidget are a wrapper of the QWindow methods such as setWindowTitle() or setWindowState().

make a layout widget to be floating ouside of mainwindow pyqt5

everyone.
I want to float a widget inside a layout of a main-window.
the widget is disappered from layout but not displayed on screen
As you can see from following code. I floated two labels 'lbl_title' and 'lbl_icon'
they seems to be floated but not displayed on screen.
Here comes my code.
If you loose commented line, then the lbl_icon and title is removed from layout but not are shown on my screen
from PyQt5.QtCore import QDir, Qt, QUrl
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)
from PyQt5.QtWidgets import QMainWindow,QWidget, QPushButton, QAction,QGridLayout
from PyQt5.QtGui import QIcon,QPixmap
import sys
from PyQt5.QtCore import *
class CommonLessonItem(QWidget):
def __init__(self,parent):
super(CommonLessonItem,self).__init__(parent)
self.lbl_title = QLabel(self)
self.lbl_description = QLabel(self)
self.lbl_icon = QLabel(self)
self.__initUI()
self.isChild = False
def __initUI(self):
#set layout
self.layout = QGridLayout(self)
self.layout.addWidget(self.lbl_title,0,0,1,19)
self.layout.addWidget(self.lbl_icon,0,19,1,1)
self.layout.addWidget(self.lbl_description,1,0,1,20)
self.lbl_icon.setWindowFlags(Qt.FramelessWindowHint|Qt.Window)
self.lbl_icon.move(100,100)
self.lbl_title.setWindowFlags(Qt.FramelessWindowHint|Qt.Window)
self.lbl_title.move(100,100)
#initialize info
self.setInfo("Title","Description",None)
self.setLayout(self.layout)
def setInfo(self,title,description,iconPath):
self.lbl_title.setText(title)
self.lbl_description.setText(description)
if(iconPath is not None):
self.lbl_icon.setPixmap(QPixmap(iconPath))
def moveEvent(self,event):
super().moveEvent(event)
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = CommonLessonItem(None)
# mw.setSize(10,200)
mw.show()
sys.exit(app.exec_())
I need your help.
Whenever a widget becomes a top level window by setting the parent to None or, like in your case, setting the Window flag (but I wouldn't suggest that approach) show() must be called.
As explained in windowFlags:
Note: This function calls setParent() when changing the flags for a window, causing the widget to be hidden. You must call show() to make the widget visible again..
Add self.lbl_icon.show() and self.lbl_title.show() after changing their window state.

How to add a QVideoWidget in Qt Designer?

I want to insert video in blue box(ui image) but I don't know how to insert video file.
My code is here.
I don't know how to add video... Just know example that make video player ...
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import uic
from PyQt5 import QtCore
from PyQt5.QtCore import QDir, Qt, QUrl, pyqtSlot
from PyQt5.QtMultimedia import QMediaContent, QMediaPlayer
from PyQt5.QtMultimediaWidgets import QVideoWidget
from PyQt5.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QLabel,
QPushButton, QSizePolicy, QSlider, QStyle, QVBoxLayout, QWidget)
dir_audience=''
dir_movie = ''
dir_export = ''
select_emotion = 'happy'
class Form(QtWidgets.QDialog):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.ui = uic.loadUi("highlight_export_form.ui", self)
self.ui.show()
self.ui.load_audience.clicked.connect(self.load_audience_clicked)
self.ui.load_movie.clicked.connect(self.load_movie_clicked)
self.ui.start_recog.clicked.connect(self.start_recog_clicked)
self.ui.radio_happy.toggled.connect(self.on_radio_button_toggled)
self.ui.radio_surprised.toggled.connect(self.on_radio_button_toggled)
def load_audience_clicked(self, event):
dir_audience, _ = QFileDialog.getOpenFileName(self, "Open Audience", QDir.homePath())
self.path_audience.setText(dir_audience)
def load_movie_clicked(self, event):
dir_movie, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath())
self.path_movie.setText(dir_movie)
def start_recog_clicked(self, event):
self.check_1.setText("start_recognition")
def on_radio_button_toggled(self):
if self.radio_happy.isChecked():
select_emotion='happy'
self.check_3.setText(select_emotion)
elif self.radio_surprised.isChecked():
select_emotion='surprised'
self.check_3.setText(select_emotion)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Form()
sys.exit(app.exec())
Thank you for reading my question.
Qt Designer does not show all the Qt widget, and often we want to add our own widget through Qt, for that there are at least 2 solutions, the first is to create a plugin and load it to Qt Designer, and the other is simpler. promote the widget, the latter is what I will show in this answer.
For this you must make certain minimum changes, I do not know what type of widget is the one you use in the blue box but you must change it to the Widget type that is in the sub-menu of the containers as shown in the following image:
after them you must right click on the widget and select Promote to ..., then a dialogue will appear, in the part of Promoted class name you must place QVideoWidget, and in the part of Header File you must place PyQt5.QtMultimediaWidgets, then press the add button and then Promote:
After that you will be able to use QVideoWidget within your application.
In the following link there is an example
Answer from here was clearer to me:
QWebKit was removed in Qt 5.6. So QWebView is no longer available. Use QWebEngineView as a replacement. In Qt Designer, just add a QWidget to your form and promote it to QWebEngineView (base class: QWidget, header: QWebEngineView). Don't forget to add webenginewidgets to your project file.
Simlar issue: want add QWebEngineView into Qt Designer
for later PySide6 to import and use .ui, exported by Qt Designer
Solution: add QWidget then Promoted to QWebEngineView
Steps
drag a new QWidget into your main ui (window)
right click QWidget -> Promoted to
new popup window, input
Base class Name: QWidget
Promoted class Name: QWebEngineView
Header File: PySide6.QtWebEngineWidgets
== parent class
Global Include: not selected
-> Screenshot
click: Add
click: Promote

Categories

Resources