Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

How to fix QPainterPath drawing tool not creating new paths each time I draw?

I have a function that when you click a point it draws a path between that clicked point and start point. I do have a checkable button (self.button) that activates and disables the tool, so I am trying to intergrate that. However, all of this has a major issue: I cannot draw multiple paths without it connecting from the last point of the original one, meaning I get this one infinetly drawable line. No matter me disabling or re-enabling the tool, it still starts from the original first drawn path.

def __init__(self, scene, button1, button2)
    self.points = []
    self.canvas = scene
    self.button = button1
    # ...

def mousePressEvent(self, event):
    if self.button.isChecked():
        if event.button() == Qt.MouseButton.RightButton:
            self.points.append(self.mapToScene(event.pos()))

            if len(self.points) > 1:
                path = QPainterPath()

                path.moveTo(self.points[0])

                for point in self.points[1:]:
                    path.lineTo(point)  # Add line segment to existing path

                # Create and configure CustomPathItem only once (outside loop)
                if not hasattr(self, "path_item"):
                    self.path_item = CustomPathItem(path)
                    self.path_item.setPen(self.pen)
                    if self.button3.isChecked():
                        self.path_item.setBrush(QBrush(QColor(self.stroke_fill_color)))
                    self.path_item.setZValue(0)
                    self.path_item.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable)
                    self.path_item.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsMovable)
                    self.canvas.addItem(self.path_item)

                # Update path of existing item within the loop
                self.path_item.setPath(path)

            super().mousePressEvent(event)

I don't know if I explained my issue, so if clarification is needed, please ask. Any help is appreciated.

QChart , How can I hide the grid and the numerical values? I only need to show the line

How can I hide the grid and the numerical values? I only need to show the line enter image description here

class myChard(QChartView):
    def __init__(self):
        super().__init__()
        self.resize(300, 300)
        self.setRenderHint(QPainter.Antialiasing)
        chart = QChart()
        self.setChart(chart)
        chart.setTitle('Simple splinechart example')
        self.getSeries(chart)
        chart.createDefaultAxes()
        chart.legend().setVisible(0)
    
    def getSeries(self, chart):
        series = QSplineSeries(chart)
        series.append([QPointF(1,1),QPointF(3,1),QPointF(999,1)])
        chart.addSeries(series)

class Window(QWidget):
    def __init__(self):
        super().__init__()
        muChart=myChard()
        layout2 = QVBoxLayout()
        layout2.addWidget(muChart)
        self.setLayout(layout2)
        self.setWindowTitle("Border Layout")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())

only need to show the line

installTranslator works only on QMainWindow, not on other windows (Pyqt)

I want to support multiple languages in my PyQt application. I have *.qm files for each language and install my QTranslator on the app instance. It works fine in my main class but doesn't work in the Settings modal. What is the problem?

this is my code:

run.py

if __name__ == "__main__":
    app = QApplication([])

    translator = QTranslator()
    translator.load(resource_path(r'app_en.qm'))
    app.installTranslator(translator)

    if API.configs.language == 'fa':
        translator.load(resource_path('app_fa.qm'))
        app.installTranslator(translator)
    
    main_window = Main()
    main_window.show()
    app.exec()

main.py

class Main(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        ui_path = resource_path('views', 'main.ui')
        loadUi(ui_path, self)
        self.config = ConfigParser()
        self.config.read("MY_CONFIG_PATH")

        self.settings_btn.clicked.connect(self.open_settings_window)

    def open_settings_window(self):
        from forms.settings import Settings

        settings_window = Settings(self.config, parent=self)
        settings_window.exec()

settings.py

class Settings(QDialog):
    def __init__(self, config, parent=None):
        super(Settings, self).__init__(parent)
        ui_file_path = resource_path('views', 'settings.ui')
        loadUi(ui_file_path, self)

In qt-designer:
enter image description here

When running app:
enter image description here

I guarantee that all this words are in my ts files.

A strange error in my project on pyqt6 and openai [closed]

сделана была визуализация с помощью qt designer, потом переписал всё на python и начала вылезать странная ошибка. Вот мой код:

import sys
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import (QApplication,
QMainWindow,
QLabel,
QDialog,
QVBoxLayout,
QTextEdit,
QPushButton,
QListWidget)
from PyQt6 import (QtGui)
from PyQt6.QtCore import Qt
from openai import OpenAI

class ChatgptBot(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('ChatGpt-bot version 3')
self.client = OpenAI(
api_key="my_api_key",
)
self.initUI()

    def initUI(self):
        self.setWindowTitle('ChatGpt-bot version 3')
        self.setWindowIcon(QtGui.QIcon('chatgpt.jpg')
        self.setStyleSheet('''
                            background-color: qlineargradient(spread:pad, x1:1, y1:1, x2:0, y2:0, stop:0
    
                            rgba(81, 0, 135, 255), stop:0.427447 rgba(41, 61, 132, 235), stop:1 rgba(155, 79, 165, 255));
                             ''')
        
        self.setFixedSize(802, 640)
    
    
        self.label = QLabel('Default (GPT-3.5)', self)
        self.label.resize(802, 60)
        self.label.setStyleSheet('''
                                background-color: rgb(0, 0, 0);
                                border-color: rgb(20, 20, 20);
                                font: 10pt "MV Boli";
    
                                color: rgb(255, 255, 255);
                                ''')
        
    
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    
        self.label.setEnabled(False)
    
    
        self.pixmap = QPixmap('logo.png')
        self.image = QLabel(self)
        self.image.move(270, 0)
        self.image.resize(64, 60)
    
        self.image.setPixmap(self.pixmap)
    
        self.listWidget = QListWidget(self)
        self.listWidget.resize(751, 451)
        self.listWidget.move(20, 70)
        self.listWidget.setStyleSheet('''
                                    background-color: rgba(255, 255, 255, 60);
                                    border: 1px solid rgba(255, 255, 255, 40);
                                    border-radius: 10%;
                                    ''')
    
        self.pushButton = QPushButton('↵', self)
        self.pushButton.resize(61, 40)
        self.pushButton.move(710, 560)
        self.pushButton.setStyleSheet('''
                                    border-color: 1px rgb(255, 255, 255);)
                                    ''')
        
    
        self.textEdit = QTextEdit(self)
        self.textEdit.resize(670, 71)
        self.textEdit.move(20, 540)
        self.textEdit.setStyleSheet('''
                                    background-color: rgba(255, 255, 255, 30);
                                    border: 1px solid rgba(255, 255, 255, 40);
                                    border-radius: 7%;
                                    ''')
    
    
        self.dialog = QDialog(self)
        self.dialog.setWindowTitle("Как к вам обращаться?")
    
        self.dialog.setFixedSize(300, 100)
    
        self.layout = QVBoxLayout(self.dialog)
        self.label = QLabel("Введите ваше имя или как к вам обращаться:")
    
        self.label.setStyleSheet('''background-color: rgba(255, 255, 255, 60);
                                        border: 1px solid rgba(255, 255, 255, 40);
                                        border-radius: 10%;''')
    
        self.line_edit = QTextEdit()
        self.line_edit.setStyleSheet('''background-color: rgba(255, 255, 255, 60);
                                        border: 1px solid rgba(255, 255, 255, 40);
                                        border-radius: 7p;''')
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.line_edit)
        self.ok_button = QPushButton("OK")
        self.ok_button.setStyleSheet('''background-color: rgba(255, 255, 255, 60);
                                        border-radius: 100px;
                                        border-color: 1px rgb(255, 255, 255);''')
        self.ok_button.clicked.connect(self.dialog.accept)
        self.layout.addWidget(self.ok_button)
        self.ok_button.setStyleSheet('''border-color: 1px rgb(255, 255, 255);''')
        self.dialog.exec()
    
    
        if self.line_edit.toPlainText().replace(' ', '') ==  '':
            self.user_name = "Пользователь"
        else:
            self.user_name = self.line_edit.toPlainText().replace('\n', ' ')
    
    
        self.pushButton.clicked.connect(self.req)
        self.listWidget.setWordWrap(True)
        
    def chatgpt_conversation(self, conversation_log):
        response = self.client.chat.completions.create(
            model='gpt-3.5-turbo',
            messages=conversation_log
        )
    
        conversation_log.append({
            'role': response.choices[0].message.role, 
            'content': response.choices[0].message.content.strip()
        })
        return conversation_log
    
    def req(self):
        self.request = self.textEdit.toPlainText()
    
        if self.request != '':
            self.listWidget.addItem(f'{self.user_name}: {self.request}')
            self.conversations = []
            self.question = self.textEdit.toPlainText()
            self.conversations.append({'role': 'user', 'content': self.question})
            self.conversations = self.chatgpt_conversation(self.conversations)
            self.final = self.conversations[-1]['content'].strip()
            self.listWidget.addItem(f'ChatGpt: {self.final}')
    
            self.textEdit.setText('')
            
    def copy_selected_item(self):
        selected_item = self.listWidget.currentItem()
    
        if selected_item:
            text_to_copy = selected_item.text()
            clipboard = QApplication.clipboard()
            clipboard.setText(text_to_copy)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = ChatgptBot()
ex.show()
sys.exit(app.exec())

вылезает такая ошибка:

Traceback (most recent call last): File "c:\Users\├хюЁушщ\Desktop\pyqt_project\test.py", line 130, in req self.conversations = self.chatgpt_conversation(self.conversations) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\├хюЁушщ\Desktop\pyqt_project\test.py", line 112, in chatgpt_conversation response = self.client.chat.completions.create( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\├хюЁушщ\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_utils_utils.py", line 299, in wrapper return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\├хюЁушщ\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\resources\chat\completions.py", line 598, in create return self._post( ^^^^^^^^^^^ File "C:\Users\├хюЁушщ\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_base_client.py", line 1055, in post return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\├хюЁушщ\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_base_client.py", line 834, in request return self._request( ^^^^^^^^^^^^^^ File "C:\Users\├хюЁушщ\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai_base_client.py", line 877, in _request raise self._make_status_error_from_response(err.response) from None

Я много чего попробовал, но не помогло ничего. Очень нужна помощь Подскажите что не так

python pyinstaller pyqt add custom icons to the interface

I have searched everywhere, I can't figure out how to add my own icons to the interface.

I don't need to know how to change the application icon or the title bar, what I need is for PyInstaller to add to the executable the images I use for buttons in the GUI once compiled.

The best I found was this, but it doesn't work:

pyinstaller --clean --onefile --noconsole --icon="media/icon.png" -i="media/icon.png" --add-data="media/*;." main.py

That my icons are shown in the buttons, but not the default PyQt icons, but the customized ones.

Why instantiating a QWidget object in PyQt5 will cause a crash while running?

I don't know that why instantiating a QWidget object in PyQt5 will cause a crash while running?

I try to solve the problem by simplify code (Code 1 and Code 2 to Code 3). However, an issue has confused me for a while.


If you don't want to look at process of simplicification, you can skip it to Code 3.


In the following code, it will not cause a crash.

Code 1:

import copy
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import QRect, QObject
from PyQt5 import QtCore
from PyQt5 import Qt
from PyQt5 import QtGui
    
class QWidgetChecker:
    @staticmethod
    def Exist(
            obj  
    ) -> bool:
        return obj != None
    
class QWidgetHandler:
    @staticmethod
    def SetGeometry(
            obj,
            position
    ):  
        if QWidgetChecker.Exist(obj) == False:
            raise Exception("ERROR!!! Object does NOT exists.")     
        obj.setGeometry(position)
        return obj
    
    def Create(
            self
    ):
        self.mainWindow = QWidget()
        return self
           
class QApplicationHandler(QWidgetHandler):   
    def __init__(self):
        super().__init__()
    def Clear(self):
        if QApplication.instance():
            QApplication.instance().exit()
    def CreateWindow(
            self,
            title
    ):
        self.Clear()
        self.app = QApplication(sys.argv)
        self.mainWindow = QMainWindow()
        self.mainWindow.setWindowTitle(title)
        return self
    def Show(
            self
    ):
        if QWidgetChecker.Exist(self.mainWindow) == False:
            raise Exception("ERROR!!! Object does NOT exists.")
        self.mainWindow.show()
    def SysExit(
            self
    ):
        if QWidgetChecker.Exist(self.app) == False:
            raise Exception("ERROR!!! Object does NOT exists.")
        sys.exit(self.app.exec_())
        
    def Close(
            self
    ):
        if QWidgetChecker.Exist(self.mainWindow) == False:
            raise Exception("ERROR!!! Object does NOT exists.")
        self.mainWindow.close()
        
def GetInfo(obj) : return [obj,type(obj)]

if __name__ == '__main__':

    rectMainWindow = QRect(0,0,1000,1000)
    
    inst =  QApplicationHandler()

    # widget = QWidget()
    
    inst = inst.CreateWindow('title')
    
    inst.mainWindow = QWidgetHandler.SetGeometry( inst.mainWindow ,rectMainWindow )
    
    # inst.mainWindow.setCentralWidget( widget )
    
    
    inst.Show()
    inst.SysExit()

However, after I uncomment the following statement,

widget = QWidget()

instantiating a QWidget object in PyQt5.

It will crash while running with Anaconda Spyder Kernel. See the following code.

Code 2:

import copy
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import QRect, QObject 
from PyQt5 import QtCore
from PyQt5 import Qt
from PyQt5 import QtGui
    
class QWidgetChecker:
    @staticmethod
    def Exist(
            obj  
    ) -> bool:
        return obj != None
    
class QWidgetHandler:
    @staticmethod
    def SetGeometry(
            obj,
            position
    ):  
        if QWidgetChecker.Exist(obj) == False:
            raise Exception("ERROR!!! Object does NOT exists.")       
        obj.setGeometry(position)
        return obj
         
class QApplicationHandler(QWidgetHandler):   
    def __init__(self):
        super().__init__()
    def Clear(self):
        if QApplication.instance():

            QApplication.instance().exit()
    def CreateWindow(
            self,
            title
    ):
        self.Clear()
        self.app = QApplication(sys.argv)
        self.mainWindow = QMainWindow()
        self.mainWindow.setWindowTitle(title)
        return self
    def Show(
            self
    ):
        if QWidgetChecker.Exist(self.mainWindow) == False:
            raise Exception("ERROR!!! Object does NOT exists.")
        self.mainWindow.show()
    def SysExit(
            self
    ):
        if QWidgetChecker.Exist(self.app) == False:
            raise Exception("ERROR!!! Object does NOT exists.")
        sys.exit(self.app.exec_())
        
    def Close(
            self
    ):
        if QWidgetChecker.Exist(self.mainWindow) == False:
            raise Exception("ERROR!!! Object does NOT exists.")
        self.mainWindow.close()
        
def GetInfo(obj) : return [obj,type(obj)]

if __name__ == '__main__':

    rectMainWindow = QRect(0,0,1000,1000)
    
    inst =  QApplicationHandler()

    widget = QWidget()
    
    inst = inst.CreateWindow('title')
    
    inst.mainWindow = QWidgetHandler.SetGeometry( inst.mainWindow ,rectMainWindow )
    
    # inst.mainWindow.setCentralWidget( widget )
    
    inst.Show()
    inst.SysExit()

I tried to reduce it, making the code as follows.

Code 3:

from PyQt5.QtWidgets import QWidget

if __name__ == '__main__':

    widget = QWidget()    
    widget.show()
    

IDE

Anaconda
Spyder
Console

I google it.

In the PyQt Official Docs, QWidget in PyQt5

it says that to show a QWidget one just have to instantiate QWidget object then call the show method of QWidget class.


I wonder that I have missed anything or have misread the docs.

Thank you for reply. Any replies are appreciated.

Text in QLabel do not increase the QDialog

This problem is an example to improve the understanding of layout and size policy. In this example code I do set the width of a QDialog to a minimum and maximum. This works. I don't touch the height of the dialog.

The problem is that the text in a QLabel is to much to fit into the dialog but the dialog do not increase its height to fit the whole label.

Which component need to change its behavior: The dialog, the layout, the label? Do I need to change the size policy or something else?

#!/usr/bin/env python3
import sys
import this
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


class MyDialog(QDialog):
    def __init__(self):
        super().__init__()

        self.setMinimumWidth(200)
        self.setMaximumWidth(400)

        wdg = QLabel(self)
        wdg.setWordWrap(True)

        # Zen of Python in Rot13
        wdg.setText(this.s.replace('\n', ' ') + " THE END")

        layout = QVBoxLayout(self)
        layout.addWidget(wdg)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    dlg = MyDialog()
    dlg.show()
    sys.exit(app.exec())

enter image description here

How to zoom out QGraphicsView and put scene under mouse?

When QGraphicsScene's size is smaller than the size of QGraphicsView during zooming, the scene will be centered by default, like the pic below.

enter image description here

I know we can use setAlignment(Qt.AlignTop | Qt.AlignLeft) to align the scene to top left, but how can I put the scene under mouse when zooming out? Just like this:

enter image description here

Any help will be appreciated!

❌
❌