Why the paintEvent is called repetitively in PySide6
In the below small piece of code why does the paintEvent
method is called repetitively?
The print(f'paint {datetime.now()}')
line confirms that the paintEvent
method is called continuously.
#!/usr/bin/env python3.10
import sys
import random
from datetime import datetime
from PySide6.QtWidgets import (QApplication, QMainWindow,
QLabel, QWidget)
from PySide6.QtCore import (Qt, QRect, QPoint)
from PySide6.QtGui import (QColor, QPen, QBrush, QPainter,
QPixmap)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.label = QLabel()
self.pixmap = QPixmap(500, 500)
self.pixmap.fill(Qt.white)
self.label.setPixmap(self.pixmap)
self.setCentralWidget(self.label)
def paintEvent(self, event):
print(f'paint {datetime.now()}')
self.pixmap = self.label.pixmap()
painter = QPainter(self.pixmap)
pen= QPen()
pen.setWidth(3)
painter.setPen(pen)
painter.drawRect(100, 100, 300, 300)
self.label.setPixmap(self.pixmap)
painter.end()
if __name__ == "__main__":
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
app.exec()
How to prevent the paintEvent
method unnecessary calls?
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
how do I dissable debian python path/recursion limit
so, as of late, I've been having path length limit and recursion limit issues, so I really need to know how to disable these.
I can't even install modules like discord.py!!!!
-
TypeError: 'float' object cannot be interpreted as an integer on linspace
TypeError Traceback (most recent call last) d:\website\SpeechProcessForMachineLearning-master\SpeechProcessForMachineLearning-master\speech_process.ipynb Cell 15' in <cell line: 1>() -->1 plot_freq(signal, sample_rate) d:\website\SpeechProcessForMachineLearning-master\SpeechProcessForMachineLearning-master\speech_process.ipynb Cell 10' in plot_freq(signal, sample_rate, fft_size) 2 def plot_freq(signal, sample_rate, fft_size=512): 3 xf = np.fft.rfft(signal, fft_size) / fft_size ----> 4 freq = np.linspace(0, sample_rate/2, fft_size/2 + 1) 5 xfp = 20 * np.log10(np.clip(np.abs(xf), 1e-20, 1e100)) 6 plt.figure(figsize=(20, 5)) File <__array_function__ internals>:5, in linspace(*args, **kwargs) File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\function_base.py:120, in linspace(start, stop, num, endpoint, retstep, dtype, axis) 23 @array_function_dispatch(_linspace_dispatcher) 24 def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, 25 axis=0): 26 """ 27 Return evenly spaced numbers over a specified interval. 28 (...) 118 119 """ --> 120 num = operator.index(num) 121 if num < 0: 122 raise ValueError("Number of samples, %s, must be non-negative." % num) TypeError: 'float' object cannot be interpreted as an integer
What solution about this problem?
-
IndexError: list index out of range with api
all_currencies = currency_api('latest', 'currencies') # {'eur': 'Euro', 'usd': 'United States dollar', ...} all_currencies.pop('brl') qtd_moedas = len(all_currencies) texto = f'{qtd_moedas} Moedas encontradas\n\n' moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars'] while len(moedas_importantes) != 0: for codigo, moeda in all_currencies.items(): if codigo == moedas_importantes[0]: cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date'] texto += f'{moeda} ({codigo.upper()}) = R$ {cotacao} [{data}]\n' moedas_importantes.remove(codigo) if len(moedas_importantes) == 0: break # WITHOUT THIS LINE, GIVES ERROR
Why am I getting this error? the list actually runs out of elements, but the code only works with the if
-
How to assign two or more values to a QMap Variable in Qt
I am getting confused of how to store the values assigned from 3 different functions and storing them in a single map variable
QMap<QString,QString> TrainMap = nullptr; if(......) ( TrainMap = PrevDayTrainMap(); TrainMap = NextDayTrainMap(); TrainMap = CurrentDayTrainMap(); }
The PrevDayTrainMap,NextDayTrainMap & CurrentDayTrainMap returns a set of values with Date and the TrainIdName.I need to store all the values from prevday,currentday and nextday in the TrainMap but it stores only the currentday values to the TrainMap as it is assigned at the last.I am not sure what to do so that it doesn't overwrite.If I should merge what is the way to do it?
-
When to use qmake eval?
https://doc.qt.io/qt-5/qmake-test-function-reference.html
eval(string) Evaluates the contents of the string using qmake syntax rules and returns true. Definitions and assignments can be used in the string to modify the values of existing variables or create new definitions. For example: eval(TARGET = myapp) { message($$TARGET) }
I wondering when/why that should be used? Can't we just use
TARGET = myapp
directly? -
How to use qmake.conf?
https://doc.qt.io/qt-5/qmake-environment-reference.html mentions
qmake.conf
, but how can I use it? What is the format? What would be one use case for it? -
convert matplotlib figure to 2-D Array to show in pyqtgraph.ImageItem
i find an example in this Link which show 2-D array in pyqtgraph.ImageItem.
import matplotlib.pyplot as plt import numpy as np import pyqtgraph as pg def main(): imarray = np.random.rand(100, 100) * 515 imarray = np.clip(imarray, 0, 515) plt_example(imarray) pyqtgraph_example(imarray) def plt_example(data): plt.imshow(data, cmap='hot') c = plt.colorbar() plt.clim(0, 200) plt.show(block=False) def pyqtgraph_example(data): app = pg.mkQApp("Test") win = pg.GraphicsLayoutWidget() win.setWindowTitle('pyqtgraph example: ImageItem') win.show() # add plot with correct axis orientation and locked aspect ratio plot = win.addPlot() plot.setAspectLocked(True) plot.invertY() # Create image item img = pg.ImageItem(data, axisOrder='row-major') plot.addItem(img) # Create color bar and have it control image levels cmap = pg.colormap.getFromMatplotlib('hot') cbi = pg.ColorBarItem(colorMap=cmap) cbi.setImageItem(img, insert_in=plot) cbi.setLevels([0, 200]) # colormap range app.exec() if __name__ == "__main__": main()
i want to create matplotlib figure and plot some graph like histogram into that
import matplotlib.pyplot as plt x = [1,1,2,3,3,5,7,8,9,10, 10,11,11,13,13,15,16,17,18,18, 18,19,20,21,21,23,24,24,25,25, 25,25,26,26,26,27,27,27,27,27, 29,30,30,31,33,34,34,34,35,36, 36,37,37,38,38,39,40,41,41,42, 43,44,45,45,46,47,48,48,49,50, 51,52,53,54,55,55,56,57,58,60, 61,63,64,65,66,68,70,71,72,74, 75,77,81,83,84,87,89,90,90,91 ] plt.hist(x, bins=10)
now i looking for a way to set histogram graph to pyqtgraph.ImageItem. anyone can help me?
-
How to import __feature__ of PySide6?
from PySide6.__feature__ import snake_case, true_property from PySide6.QtWidgets import QMainWindow, QWidget, QHBoxLayout, QApplication class MainWindow(QMainWindow): def __init__(self): super().__init__() self.main_layout = QHBoxLayout() self.container = QWidget() self.container.set_layout(self.main_layout) if __name__ == '__main__': app = QApplication([]) main_window = MainWindow() main_window.show() app.exec()
I got an error message when trying to run the above code:
ModuleNotFoundError: No module named 'PySide6.__feature__'
If I break the first line into
import PySide6 from __feature__ import snake_case, true_property
the code could run but PyCharm complains that
Unresolved reference: __feature__
How could I fix it?
Thanks for your help.
-
PySide6 How to remove spacing between buttons in QHBoxLayout?
How can I remove the spacing between buttons after fixing their size?
A space is added whenever I set the Button's size.
I tried setSpacing but it does not work. Can this be done by sizePolicy or something else?
Here is my code.
from PySide6.QtCore import Qt, QSize from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setMinimumSize(QSize(800, 600)) self.setWindowTitle('Horizontal Layout') self.container = QWidget() self.horizontalLayout = QHBoxLayout() self.button_1 = QPushButton('Button 1') self.button_1.setFixedSize(QSize(70, 60)) self.button_2 = QPushButton('Button 2') self.button_2.setFixedSize(QSize(70, 60)) self.button_3 = QPushButton('Button 3') self.button_3.setFixedSize(QSize(70, 60)) self.horizontalLayout.addWidget(self.button_1) self.horizontalLayout.addWidget(self.button_2) self.horizontalLayout.addWidget(self.button_3) self.container.setLayout(self.horizontalLayout) self.setCentralWidget(self.container) app = QApplication([]) window = MainWindow() window.show() app.exec()
-
How to make Triangle obect in Windows Form?
I want to draw/make a triangle graphic that will appear right after when I run the program but I can't figure out the right command. Here's the command I use to make a rectangle object.
private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.FillRectangle(Brushes.Aquamarine, _x, _y, 100, 100); }
So when I make the object, I'll make it move automatically.
I've searched for tutorials but couldn't find anything suitable. Please help.
-
Qt Custom Paint Event Progressbar
I want to make custom progressbar on Qt.
Design of progressbar (It's PNG):
Here is the result on Qt:
Code of Pic2:
import sys, os, time from PySide6 import QtCore, QtWidgets, QtGui from PySide6.QtWidgets import * from PySide6.QtCore import * from PySide6.QtGui import * class EProgressbar(QProgressBar): valueChanged = QtCore.Signal(int) _val = 0 def __init__(self): super(EProgressbar, self).__init__(None) self.r = 15 self.setFixedHeight(40) self._animation = QtCore.QPropertyAnimation(self, b"_vallll", duration=600) self.valueChanged.connect(self.update) def setValue(self, value:int) -> None: self._animation.setStartValue(self.value()) self._animation.setEndValue(value) self._val = value self._animation.start() def value(self) -> int: return self._val def ESetValue(self, value): if self._val != value: self._val = value self.valueChanged.emit(value) _vallll = QtCore.Property(int, fget=value, fset=ESetValue, notify=valueChanged) def paintEvent(self, event: QPaintEvent) -> None: pt = QPainter();pt.begin(self);pt.setRenderHints(QPainter.Antialiasing|QPainter.TextAntialiasing) path = QPainterPath();path2 = QPainterPath(); path3 = QPainterPath() font = QFont('Helvetica', 11, weight=QFont.Bold); font.setStyleHint(QFont.Times, QFont.PreferAntialias) BRUSH_BASE_BACKGROUND, BRUSH_BASE_FOREGROUND, BRUSH_POLYGON, BRUSH_CORNER = QColor(247,247,250), QColor(255,152,91), QColor(255,191,153), QColor(203,203,205) pt.setPen(QPen(BRUSH_CORNER,1.5));pt.setBrush(BRUSH_BASE_BACKGROUND) rect = self.rect().adjusted(2,2,-2,-2)#QRect(1, 0, self.width()-2, self.height()) path.addRoundedRect(rect, self.r, self.r) #pt.setBrush(BRUSH_BASE_FOREGROUND) #path.addRect(self.rect()) path2.addRoundedRect(QRect(2,2, self._vallll/ 100 * self.width()-4, self.height()-4), self.r, self.r) #path2.addRoundedRect(QRect(20,2,10, self.height()), self.r, self.r) pt.drawPath(path) pt.setBrush(BRUSH_BASE_FOREGROUND) pt.drawPath(path2) pt.setPen(Qt.NoPen) pt.setBrush(BRUSH_POLYGON) start_x = 20 y, dx = 3, 6 polygon_width = 14 polygon_space =18 #15#18 progress_filled_width = self.value()/self.maximum()*self.width() pt.setClipPath(path2, Qt.ClipOperation.ReplaceClip) # bu olmazsa polygon taşıyor, clip yapılması lazım for i in range(100): x = start_x + (i*polygon_width) + (i*polygon_space) if x >= progress_filled_width or (x+ polygon_width >= progress_filled_width): break path2.addPolygon(QPolygon([ QPoint(x, y), QPoint(x+polygon_width, y), QPoint(x+polygon_width/2, self.height()-y), QPoint(x-polygon_width/2, self.height()-y)])) pt.drawPath(path2) pt.setFont(font) pt.setPen(Qt.white) pt.drawText(QRect(2,2,self.width()-4,self.height()-4), Qt.AlignCenter, f"%{self.value()}") pt.end() if __name__ == "__main__": app = QApplication(sys.argv) wind = QMainWindow();wind.setStyleSheet("QMainWindow{background-color:blue}");wind.setWindowTitle("EProgressBar") wind.resize(221,150) wid = QWidget();lay = QHBoxLayout(wid);lay.setAlignment(Qt.AlignCenter) e = EProgressbar();e.setValue(80) timer = QTimer(wind) def lamb(): import random e.setValue(random.randint(0,100)) timer.timeout.connect(lamb) #timer.start(1000) #e.setGeometry(QRect(10,10,170,250)) lay.addWidget(e) wind.setCentralWidget(wid) #e.setParent(wind) wind.show() sys.exit(app.exec())
This one looks good but when I set progressbar value to 0, result like this:
Notes:
- I need to use pt.setClipPath(path2, Qt.ClipOperation.ReplaceClip) else If you look closely, the polygon in the upper right has crossed the progressbar.
So I think all drawing things must be? in the same QPainterPath? When I try all the drawing in the same path (like OnePathCode) result like this: