Adding pyqtgraph to PyQt6 - pyqtgraph

So I am making a GUI using Pyqt6 and want to add graphs inside the Gui with other data, SO when I try adding the graph i get the error bellow:
call: addWidget(self, QWidget): argument 1 has unexpected type 'PlotWidget' addWidget(self, QWidget, int, int, alignment: Qt.AlignmentFlag = Qt.Alignment()): argument 1 has unexpected type 'PlotWidget' addWidget(self, QWidget, int, int, int, int, alignment: Qt.AlignmentFlag = Qt.Alignment()): argument 1 has unexpected type 'PlotWidget'
The code I have
self.plt=pyqtgraph.PlotWidget()
self.plt.plot([1,2,3,4,5],[1,2,3,4,5])
grid.addWidget(self.plt, 6, 1, 3, 3)
self.setLayout(grid) #up I have grid=QGridLayout()

I was trying to reproduce Your issue for a while.
I succeeded after I install PyQt5 and PyQt6 together in the same environment.
As #musicamante pointed out, it's important to first import PyQt6 and ONLY after that pyqtgraph.
Otherwise QT_LIB is not set properly and only guesses PyQt version from already installed packages in the environment.

Related

How to avoid RuntimeError while call __dict__ on module?

it is appearing in some big modules like matplotlib. For example expression :
import importlib
obj = importlib.import_module('matplotlib')
obj_entries = obj.__dict__
Between runs len of obj_entries can vary. From 108 to 157 (expected) entries. Especially pyplot can be ignored like some another submodules.
it can work stable during manual debug mode with len computing statement after dict extraction. But in auto it dont work well.
such error occures:
RuntimeError: dictionary changed size during iteration
python-BaseException
using clear python 3.10 on windows. Version swap change nothing at all
during some attempts some interesting features was found.
use of repr is helpfull before dict initiation.
But if module transported between classes like variable more likely lazy-import happening? For now there is evidence that not all names showing when command line interpriter doing opposite - returning what expected. So this junk of code help bypass this bechavior...
Note: using pkgutil.iter_modules(some_path) to observe modules im internal for pkgutil ModuleInfo form.
import pkgutil, importlib
module_info : pkgutil.ModuleInfo
name = module_info.name
founder = module_info.module_finder
spec = founder.find_spec(name)
module_obj = importlib.util.module_from_spec(spec)
loader = module_obj.__loader__
loader.exec_module(module_obj)
still unfamilliar with interior of import mechanics so it will be helpfull to recive some links to more detail explanation (spot on)

MyPy complains about Qt.AlignmentFlag

When I upgrade to PySide6 6.2.2, MyPy starts complaining about Qt.AlignmentFlag. Here's a small example:
from PySide6.QtGui import Qt
from PySide6.QtWidgets import QLabel, QApplication
app = QApplication()
label = QLabel("Hello, World!")
label.setAlignment(Qt.AlignCenter)
label.show()
app.exec()
That still runs fine, but MyPy complains:
$ mypy foo.py
foo.py:6: error: Argument 1 to "setAlignment" of "QLabel" has incompatible type "AlignmentFlag"; expected "Alignment"
Found 1 error in 1 file (checked 1 source file)
$
OK, I try converting the AlignmentFlag to an Alignment.
from PySide6.QtGui import Qt
from PySide6.QtWidgets import QLabel, QApplication
app = QApplication()
label = QLabel("Hello, World!")
label.setAlignment(Qt.Alignment(Qt.AlignCenter))
label.show()
app.exec()
Again, that runs fine, but MyPy now complains about the constructor.
$ mypy foo.py
foo.py:6: error: Too many arguments for "Alignment"
Found 1 error in 1 file (checked 1 source file)
$
Could someone please explain how to use Qt.Alignment and Qt.AlignmentFlag?
Until I find a better option, I'm going to assume that someone messed up the type hints in PySide6 6.2.2, and I'll just tell MyPy to ignore it.
from PySide6.QtGui import Qt
from PySide6.QtWidgets import QLabel, QApplication
app = QApplication()
label = QLabel("Hello, World!")
label.setAlignment(Qt.AlignCenter) # type: ignore
label.show()
app.exec()
Have you tried using Qt.AlignmentFlag.AlignCenter instead of Qt.AlignCenter in the setAlignment function? PySide/PyQt fills that field with the enum value you want at runtime, to have some similarity to how you would do it in C++.
Qt.AlignmentFlag is an enum class and AlignCenter is an enum value.

Why QDialog not shows any widgets until job completed? [duplicate]

This question already has answers here:
Equivalent to time.sleep for a PyQt application
(5 answers)
Closed 2 years ago.
im new to pyqt5,i tried to open dialog and push some text into that dialog
my dialog contain one plaintext ,progressbar and pushbutton
when i run the code its popup the dialog but not shown any thing ,after code execution completes its showing all the widgets and with text
but i need to open the dialog and i want update progress bar
My code
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QDialog,QPlainTextEdit,QScrollArea,QProgressBar,QPushButton)
import sys
import time
class PrograssDialog():
def ShowDialog(self,Dialogs):
try:
self.Pd=Dialogs
self.Pd.setWindowTitle("Script Excution... ")
self.Pd.resize(500,500)
self.ScrArea=QScrollArea(self.Pd)
self.ScrArea.move(0,0)
self.ScrArea.resize(500,300)
self.TextArea=QPlainTextEdit(self.Pd)
self.TextArea.move(0,0)
self.TextArea.resize(500,300)
self.TextArea.insertPlainText(str("Start : %s" % time.ctime())+"\n")
self.Prograssbar=QProgressBar(self.Pd)
self.Prograssbar.setGeometry(QtCore.QRect(0, 350, 450, 23))
self.Prograssbar.setMaximum(100)
self.Cancelbutton=QPushButton("Cancel",self.Pd)
self.Cancelbutton.setGeometry(QtCore.QRect(360, 400, 93, 28))
self.Cancelbutton.clicked.connect(self.StopExcution)
self.Pd.show()
except Exception as msg:
import sys
tb = sys.exc_info()[2]
print("Error_analysis " + str(msg)+ str(tb.tb_lineno))
def AddMessage(self,Message):
self.TextArea.insertPlainText(str(Message)+"\n")
# print("message added")
def SetPercentage(self,Number):
self.Prograssbar.setValue(Number)
# print("percent added")
def StopExcution(self):
sys.exit()
app = QApplication(sys.argv)
ui=PrograssDialog()
ui.ShowDialog(QDialog())
for i in range(100):
ui.AddMessage("Hello")
ui.SetPercentage(i)
time.sleep(0.5)
sys.exit(app.exec_())
There are various problems with your code, I'll try to address all of them.
The main reason for the issue you are facing is that no blocking functions (like time.sleep) should happen in the main Qt thread (which is the thread that shows the GUI elements and allow interactions with them); blocking functions prevent the UI to correctly draw and refresh its contents, if you want to do an operation at specific intervals, you have to use a QTimer;
You should not use a basic python object subclass for this kind of situations, especially since you're only using just one dialog; you should subclass from QDialog instead and implement
To "exit" your program you should not use sys.exit (you are already using it), but use QApplication.quit() instead; also, since you already imported sys at the beginning, there's no need to import it again in the exception;
Function and variable names should not be capitalized; while you can use any casing style you want for your own code, it's common (and highly suggested) practice to always use lowercase initials, and it's also a convention you should stick to when sharing code with others, especially on Q&A sites like StackOverflow; read more on the official Style Guide for Python Code;
Always avoid fixed geometries for children widgets: what others see on their computers will probably be very different from what you see on yours, and you might end up with an unusable interface; use layout managers instead, so that the widgets can resize themselves if required;
You added a scroll area but you never use it; since you're using the same geometry for the text area I believe that you thought you were using for that, but there's no need as the text area already is a scroll area;
Here is how the code could look like in order to achieve what you want:
import time
from PyQt5 import QtCore, QtWidgets
class ProgressDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super().__init__(parent)
layout = QtWidgets.QVBoxLayout(self)
self.textArea = QtWidgets.QPlainTextEdit()
layout.addWidget(self.textArea)
self.textArea.insertPlainText(str("Start : %s" % time.ctime())+"\n")
self.textArea.setReadOnly(True)
self.progressBar = QtWidgets.QProgressBar()
layout.addWidget(self.progressBar)
self.cancelButton = QtWidgets.QPushButton('Cancel')
layout.addWidget(self.cancelButton)
self.cancelButton.clicked.connect(QtWidgets.QApplication.quit)
self.countTimer = QtCore.QTimer()
self.countTimer.timeout.connect(self.timeout)
def startCounter(self, maximum, sleepSeconds):
self.progressBar.reset()
self.progressBar.setMaximum(maximum)
# QTimer interval is in milliseconds
self.countTimer.setInterval(sleepSeconds * 1000)
self.countTimer.start()
def timeout(self):
if self.progressBar.value() == self.progressBar.maximum():
self.countTimer.stop()
return
self.setPercentage(self.progressBar.value() + 1)
self.addMessage('Hello')
def setPercentage(self, value):
self.progressBar.setValue(value)
def addMessage(self, message):
self.textArea.insertPlainText(str(message) + '\n')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
dialog = ProgressDialog()
dialog.show()
dialog.startCounter(100, .5)
sys.exit(app.exec_())

Moving the cursor in a PyQt5 text edit doesn't work

I'm contributing to Frescboaldi, a PyQt5 application and experience problems interacting with the core text edit component.
It seems whatever I try I can't get either of setPosition or movePosition to work.
The code
cursor.insertText("Hello")
cursor.setPosition(cursor.position() - 5)
properly inserts the text Hello in the document but leaves the cursor at the end of the inserted text (instead of moving it to the left by 5 characters). The first line proves that cursor, textedit and document are set up properly. trying movePosition doesn't have any effect either.
The actual goal is to insert some text, have it selected and the cursor at the end of the selection as can be seen in https://github.com/wbsoft/frescobaldi/blob/master/frescobaldi_app/cursortools.py#L179
Am I doing anything wrong here? Could this be a bug in Qt/PyQt? Or could this be an issue in PyQt5?
[Edit:] I've now confirmed with a minimal app example that the problem can't be in the larger construction of the application. In the following mini app neither setPosition nor movePosition has any effect - while insertText works well:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QTextEdit
def main():
app = QApplication(sys.argv)
w = QTextEdit()
w.setWindowTitle('Manipulate cursor')
cursor = w.textCursor()
cursor.insertText("Hello World")
# neither of the following commands have any effect
cursor.setPosition(cursor.position() - 5)
cursor.movePosition(cursor.movePosition(cursor.Left, cursor.KeepAnchor, 3))
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You are working on a local copy of the text cursor returned by w.textCursor. You should call w.setTextCursor(cursor) at the end to change the visible cursor.
A second problem is that you use the output of movePosition to call movePosition again, which is not allowed:
cursor.movePosition(cursor.movePosition(cursor.Left, cursor.KeepAnchor, 3))
should be
cursor.movePosition(cursor.Left, cursor.KeepAnchor, 3)
Note that I tested it in Qt (not PyQt), but that should not make any difference, which successfully selected lo of Hello world.

looking for example for QCompleter with segmented completion / tree models

The PySide docs include this section on QCompleter with tree models:
PySide.QtGui.QCompleter can look for completions in tree models, assuming that any item (or sub-item or sub-sub-item) can be unambiguously represented as a string by specifying the path to the item. The completion is then performed one level at a time.
Let’s take the example of a user typing in a file system path. The model is a (hierarchical) PySide.QtGui.QFileSystemModel . The completion occurs for every element in the path. For example, if the current text is C:\Wind , PySide.QtGui.QCompleter might suggest Windows to complete the current path element. Similarly, if the current text is C:\Windows\Sy , PySide.QtGui.QCompleter might suggest System .
For this kind of completion to work, PySide.QtGui.QCompleter needs to be able to split the path into a list of strings that are matched at each level. For C:\Windows\Sy , it needs to be split as “C:”, “Windows” and “Sy”. The default implementation of PySide.QtGui.QCompleter.splitPath() , splits the PySide.QtGui.QCompleter.completionPrefix() using QDir.separator() if the model is a PySide.QtGui.QFileSystemModel .
To provide completions, PySide.QtGui.QCompleter needs to know the path from an index. This is provided by PySide.QtGui.QCompleter.pathFromIndex() . The default implementation of PySide.QtGui.QCompleter.pathFromIndex() , returns the data for the edit role for list models and the absolute file path if the mode is a PySide.QtGui.QFileSystemModel.
But I can't seem to find an example showing how to do this. Can anyone point me at an example I can use as a starting point? (In my investigation it looks like maybe the hard part is the tree model rather than the QCompleter)
It looks like you would need to provide these functions:
ability to split a string into segments (for the example given, C:\Windows\Sy to ['C:','Windows','Sy']
the ability to specify the list of items that include the last segment (e.g. all the items included in ['C:','Windows']
I found an example for the basic functionality of QCompleter and have been able to tweak the basics fine (see below), I just don't know how to go about implementing a tree model type application.
'''based on
http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?index=403&key=QCompleterQLineEdit'''
from PySide.QtGui import *
from PySide.QtCore import *
import sys
def main():
app = QApplication(sys.argv)
edit = QLineEdit()
strList = '''
Germany;Russia;France;
french fries;frizzy hair;fennel;fuzzball
frayed;fickle;Frobozz;fear;framing;frames
Franco-American;Frames;fancy;fire;frozen yogurt
football;fnord;foul;fowl;foo;bar;baz;quux
family;Fozzie Bear;flinch;fizzy;famous;fellow
friend;fog;foil;far;flower;flour;Florida
'''.replace('\n',';').split(";")
strList.sort(key=lambda s: s.lower())
completer = QCompleter(strList,edit)
completer.setCaseSensitivity(Qt.CaseInsensitive)
edit.setWindowTitle("PySide QLineEdit Auto Complete")
edit.setCompleter(completer)
edit.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I couldn't find a good example for what I wanted, but I figured out how to adapt the Qt TreeModel example to using a QCompleter:
https://gist.github.com/jason-s/9dcef741288b6509d362
The QCompleter is the easy part, you just have to tell it how to split a path into segments, and then how to get from a particular entry in the model back to a path:
class MyCompleter(QtGui.QCompleter):
def splitPath(self, path):
return path.split('/')
def pathFromIndex(self, index):
result = []
while index.isValid():
result = [self.model().data(index, QtCore.Qt.DisplayRole)] + result
index = index.parent()
r = '/'.join(result)
return r
Aside from that, you have to configure the QCompleter properly, telling it how to get from a model item to a text string. Here I set it up to use the DisplayRole and to use column 0.
edit = QtGui.QLineEdit()
completer = MyCompleter(edit)
completer.setModel(model)
completer.setCompletionColumn(0)
completer.setCompletionRole(QtCore.Qt.DisplayRole)
completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
As the documentation for QCompleter says you can provide two models: a list model or a tree model.
Example for list model, after your example:
from PySide import QtGui
app = QtGui.QApplication([])
edit = QtGui.QLineEdit()
strList = "Germany;Russia;France;Norway".split(";")
completer = QtGui.QCompleter(strList)
edit.setCompleter(completer)
edit.show()
app.exec_()
works:
And as a tree model:
from PySide import QtGui, QtCore
app = QtGui.QApplication([])
edit = QtGui.QLineEdit()
model = QtGui.QFileSystemModel()
model.setFilter(QtCore.QDir.AllDirs | QtCore.QDir.Drives)
model.setRootPath('')
completer = QtGui.QCompleter(model, edit)
edit.setCompleter(completer)
edit.show()
app.exec_()
for some strange reason nothing is displayed here. Will investigate later.

Resources