Skip to content

Qt for Python

For discussion and questions about Qt for Python (PySide & Shiboken)

3.3k Topics 14.5k Posts
  • Simplest way for two-way binding a text field

    Solved pyside 26 Feb 2021, 08:30
    0 Votes
    6 Posts
    3k Views
    @xtofl In QML the binding is unidirectional: from right to left: Foo { id: foo a: bar.b } This binding indicates that every time the property "b" (which must be a signal) of the object "bar" then the property "a" of the object "foo" will be updated with that value. In python it would be something like: bar.b_Signal.connect(lambda: setattr(foo, "a", foo.b)) If you want to implement a 2-way binding then create a class that listens when one of those properties change ("a" or "b") and then updates the other.
  • Fontsize on 'some' windows machines too big

    Unsolved 1 Mar 2021, 09:18
    0 Votes
    3 Posts
    311 Views
    Yeah, that seemed to be the case. I've added: os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" qapp = QApplication(sys.argv) qapp.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) and now it looks normal at the clients side. (I don't have a similar system, so I can't really test.) Next step is to make QT aware of the Zoom factor as set in Windows. Any hints on that? Bouke
  • 0 Votes
    2 Posts
    1k Views
    It depends on how you create your project/file. If you create a project of the type Application "Qt for Python", you will end up with a main.py where PySide2 is imported and I could not find the template file in the Qt installation files. If you simply create a new file of the type Python | Python Class you will be offered to choose between PyQt5 and Pyside2. The template file is in your Qt installation folder: Qt\Tools\QtCreator\share\qtcreator\templates\wizards\classes\python. Sorry, QtCreator is great but not perfect for Python yet from what I can tell :-/
  • 3D in PySide questions

    Solved pyside python 24 Feb 2021, 02:45
    0 Votes
    2 Posts
    455 Views
    Hi, You have both Qt's OpenGL module and Qt3D at your disposal for that.
  • 0 Votes
    4 Posts
    585 Views
    @anonyumu It seems that it is a PySide6 bug that has changed the name of the kwargs, for example using help you get the names of the kwargs: dir(QSpacerItem) output Help on class QSpacerItem in module PySide6.QtWidgets: class QSpacerItem(QLayoutItem) | QSpacerItem(self, w: int, h: int, hData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum, vData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum) -> None | | QSpacerItem(self, w: int, h: int, hData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum, vData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum) -> None | | Method resolution order: | QSpacerItem | QLayoutItem | Shiboken.Object | builtins.object | | Methods defined here: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __init__(self, w: int, h: int, hData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum, vData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum) -> None | __init__(self, w: int, h: int, hData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum, vData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum) -> None | | Initialize self. See help(type(self)) for accurate signature. | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | changeSize(self, w: int, h: int, hData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum, vData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum) -> None | changeSize(self, w: int, h: int, hData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum, vData: PySide6.QtWidgets.QSizePolicy.Policy = PySide6.QtWidgets.QSizePolicy.Policy.Minimum) -> None | | expandingDirections(self) -> PySide6.QtCore.Qt.Orientations | expandingDirections(self) -> PySide6.QtCore.Qt.Orientations | | geometry(self) -> PySide6.QtCore.QRect | geometry(self) -> PySide6.QtCore.QRect | | isEmpty(self) -> bool | isEmpty(self) -> bool | | maximumSize(self) -> PySide6.QtCore.QSize | maximumSize(self) -> PySide6.QtCore.QSize | | minimumSize(self) -> PySide6.QtCore.QSize | minimumSize(self) -> PySide6.QtCore.QSize | | setGeometry(self, arg__1: PySide6.QtCore.QRect) -> None | setGeometry(self, arg__1: PySide6.QtCore.QRect) -> None | | sizeHint(self) -> PySide6.QtCore.QSize | sizeHint(self) -> PySide6.QtCore.QSize | | sizePolicy(self) -> PySide6.QtWidgets.QSizePolicy | sizePolicy(self) -> PySide6.QtWidgets.QSizePolicy | | spacerItem(self) -> PySide6.QtWidgets.QSpacerItem | spacerItem(self) -> PySide6.QtWidgets.QSpacerItem | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from Shiboken.ObjectType | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from QLayoutItem: | | alignment(self) -> PySide6.QtCore.Qt.Alignment | alignment(self) -> PySide6.QtCore.Qt.Alignment | | controlTypes(self) -> PySide6.QtWidgets.QSizePolicy.ControlTypes | controlTypes(self) -> PySide6.QtWidgets.QSizePolicy.ControlTypes | | hasHeightForWidth(self) -> bool | hasHeightForWidth(self) -> bool | | heightForWidth(self, arg__1: int) -> int | heightForWidth(self, arg__1: int) -> int | | invalidate(self) -> None | invalidate(self) -> None | | layout(self) -> PySide6.QtWidgets.QLayout | layout(self) -> PySide6.QtWidgets.QLayout | | minimumHeightForWidth(self, arg__1: int) -> int | minimumHeightForWidth(self, arg__1: int) -> int | | setAlignment(self, a: PySide6.QtCore.Qt.Alignment) -> None | setAlignment(self, a: PySide6.QtCore.Qt.Alignment) -> None | | widget(self) -> PySide6.QtWidgets.QWidget | widget(self) -> PySide6.QtWidgets.QWidget | | ---------------------------------------------------------------------- | Data descriptors inherited from QLayoutItem: | | align | | ---------------------------------------------------------------------- | Methods inherited from Shiboken.Object: | | __getattribute__(self, name, /) | Return getattr(self, name). | | ---------------------------------------------------------------------- | Data descriptors inherited from Shiboken.Object: | | __dict__ Considering the above then the solution is: QSpacerItem(0, 0, hData = QSizePolicy.Expanding) QSpacerItem(0, 0, vData = QSizePolicy.Fixed) Same for scaled: help(QPixmap.scaled) Help on method_descriptor: scaled(...) scaled(self, s: PySide6.QtCore.QSize, aspectMode: PySide6.QtCore.Qt.AspectRatioMode = PySide6.QtCore.Qt.AspectRatioMode.IgnoreAspectRatio, mode: PySide6.QtCore.Qt.TransformationMode = PySide6.QtCore.Qt.TransformationMode.FastTransformation) -> PySide6.QtGui.QPixmap scaled(self, w: int, h: int, aspectMode: PySide6.QtCore.Qt.AspectRatioMode = PySide6.QtCore.Qt.AspectRatioMode.IgnoreAspectRatio, mode: PySide6.QtCore.Qt.TransformationMode = PySide6.QtCore.Qt.TransformationMode.FastTransformation) -> PySide6.QtGui.QPixmap then QPixmap().scaled(QSize(640, 480), aspectMode=Qt.AspectRatioMode.IgnoreAspectRatio) QPixmap().scaled(QSize(640, 480), mode=Qt.TransformationMode.FastTransformation)
  • open new window in pyqt5

    Unsolved 8 Apr 2020, 09:26
    0 Votes
    9 Posts
    14k Views
    Hello guys. I have another but so close question. The main problem is all this tactics is not working on qtdesigner based .py files. For examples: [image: 2b92326f-843b-483a-b346-fe93395b9a42.png] As you see there is just one buton. There is nothing more. Just i wanted, when i push the button launch the same things. This the first untouched code: -- coding: utf-8 -- Form implementation generated from reading ui file 'x.ui' Created by: PyQt5 UI code generator 5.15.2 WARNING: Any manual changes made to this file will be lost when pyuic5 is run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(260, 226) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(90, 120, 75, 23)) self.pushButton.setObjectName("pushButton") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 260, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "PushButton")) if name == "main": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) I just copied the class [image: 4d709571-c5fa-4612-a8a1-6c8a55eefadf.png] It's offer me build init [image: dd467fba-71fa-40d6-ba29-5ca14ca0b071.png] I aceepted [image: 7dc5e956-78cc-4d9b-8e79-a337b150454c.png] Finally any solution didn't help me. Especially designer based codes hasn't solution. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow2(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(260, 226) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(90, 120, 75, 23)) self.pushButton.setObjectName("pushButton") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 260, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "PushButton")) class Ui_MainWindow(object): def init(self): self.nextWindow = Ui_MainWindow2() def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(260, 226) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(90, 120, 75, 23)) self.pushButton.setObjectName("pushButton") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 260, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.pushButton.setText(_translate("MainWindow", "PushButton")) self.pushButton.clicked.connect(self.launcher) def launcher(self): self.nextWindow.show() if name == "main": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
  • This topic is deleted!

    Unsolved 20 Feb 2021, 19:39
    0 Votes
    7 Posts
    40 Views
  • Explicitly running a procedure in a different QThread

    Unsolved 11 Feb 2021, 13:15
    0 Votes
    13 Posts
    877 Views
    Oh I see, I did not get the while part. Just to sum up a bit so we are on the same line: you have API calls that are done while also building your GUI the result of that call shall trigger further widget creation these widget creation cannot happen before your main widget is fully initialized Is that all correct ? Will you have other widgets created after that ?
  • Qt -platform webgl support in pyqt

    Unsolved qt for python 11 Feb 2021, 14:29
    0 Votes
    10 Posts
    2k Views
    Looks like this problem goes deeper than a simple pyqt issue. I have posted my issue on SO: https://stackoverflow.com/questions/66222702/how-to-get-webgl-support-in-pyqt5 And reported as a bug on qt jira: https://bugreports.qt.io/browse/QTBUG-91162 With additional informations related to javascript logs.
  • 0 Votes
    8 Posts
    1k Views
    @JonB after some search I think its a good way to use it but sadly i cant find any good example of it in python (I can prove a set of line edits for every line, because some lines are so big and its make the program hard to work with)
  • 0 Votes
    5 Posts
    2k Views
    I haven't found it already translated but it's not the most complicated C++ code. The translation to Python is pretty straightforward.
  • make user able to edit qtreewidget

    Unsolved 17 Feb 2021, 16:29
    0 Votes
    4 Posts
    409 Views
    @iwrwrc So --- as far as I know there is nothing supplied for this --- you have to do the code yourself. You could, for example, have an Add button, or as @SGaist wrote probably best if you do it via right-click context menus on nodes/leaves to insert/edit/delete.
  • App crashes on QCheckBox.setChecked()

    Solved 17 Feb 2021, 13:13
    0 Votes
    3 Posts
    781 Views
    @jsulm Yes, I did debug it and there was no stack trace, the app just crashed silently. But your reply gave me a good hint. I checked the connected slot and found that it uses the index of the old model while it should have been switched to a new proxy model. This solved the issue. Thanks a lot for the tip!
  • Keep Focus of textbrowser on top?

    Unsolved 16 Feb 2021, 18:11
    0 Votes
    1 Posts
    181 Views
    No one has replied
  • QTreeView doesn't expand

    Solved 16 Feb 2021, 16:16
    0 Votes
    3 Posts
    1k Views
    @mrjj Thanks a lot! This seems to work.
  • QTreeView sorting questions

    Solved 15 Feb 2021, 17:04
    0 Votes
    5 Posts
    2k Views
    Found the solution and posted it to StackOverflow. Pasting it here as well. class SortingModel(QSortFilterProxyModel): def lessThan(self, source_left: QModelIndex, source_right: QModelIndex): file_info1 = self.sourceModel().fileInfo(source_left) file_info2 = self.sourceModel().fileInfo(source_right) if file_info1.fileName() == "..": return self.sortOrder() == Qt.SortOrder.AscendingOrder if file_info2.fileName() == "..": return self.sortOrder() == Qt.SortOrder.DescendingOrder if (file_info1.isDir() and file_info2.isDir()) or (file_info1.isFile() and file_info2.isFile()): return super().lessThan(source_left, source_right) return file_info1.isDir() and self.sortOrder() == Qt.SortOrder.AscendingOrder The code for initializing view and model: model = QFileSystemModel() model.setRootPath('.') model.setFilter(QDir.NoDot | QDir.AllEntries) model.sort(0, Qt.SortOrder.AscendingOrder) sorting_model = SortingModel() sorting_model.setSourceModel(model) view.tree_view.setModel(sorting_model) view.tree_view.setRootIndex(sorting_model.mapFromSource(model.index('.'))) view.tree_view.header().setSortIndicator(0, Qt.AscendingOrder) view.tree_view.setSortingEnabled(True)
  • Use uic.loadUi and get mouseMoveEvent

    Solved 16 Feb 2021, 09:48
    0 Votes
    15 Posts
    1k Views
    @Mikeeeeee said in Use uic.loadUi and get mouseMoveEvent: Please give a full-fledged example. I will not. class MyEventFilter(QObject): def eventFilter(QObject obj, QEvent event): print("HERE") return QObject::eventFilter(obj, event) ... myEventFilter = MyEventFilter() self.ui.installEventFilter(myEventFilter)
  • How to track user inactivity

    Unsolved 16 Feb 2021, 09:25
    0 Votes
    4 Posts
    520 Views
    @Mikeeeeee So you will have to write code to detect exactly those things you want to monitor. Probably through an event filter. And if none arrive the user is inactive, in those terms. I don't know what else to say.
  • save changes done to items in a treewidget

    Unsolved 15 Feb 2021, 22:13
    0 Votes
    2 Posts
    258 Views
    @iwrwrc Changes made from a QTreeWidget should go through to the underlying model and be saved there. They will persist across tab changes, unless you have something wrong in your code.
  • Display images(or image streams) in QML from Python

    Unsolved 9 Feb 2021, 23:16
    0 Votes
    6 Posts
    3k Views
    Can you pass a singleton into a QML register Type? or rather import a singleton so that this python file can access the continuously changing data from another python file or class instance. For example "from main import myTestClasse" so far the data is not updating to match the singleton myTestClasse and was wondering if there is an extra step that needs to be taken? From the example listed above with modifications :... """ import numpy as np import threading #from PySide6 import Qt import cv2 """ from PySide6 import QtCore, QtGui, QtQml from PySide6.QtCore import QObject, Signal, Slot, Property from main import myTestClasse def max_rgb_filter(image): # split the image into its BGR components (B, G, R) = cv2.split(image) # find the maximum pixel intensity values for each # (x, y)-coordinate,, then set all pixel values less # than M to zero M = np.maximum(np.maximum(R, G), B) R[R < M] = 0 G[G < M] = 0 B[B < M] = 0 # merge the channels back together and return the image return cv2.merge([B, G, R]) gray_color_table = [QtGui.qRgb(i, i, i) for i in range(256)] class CVCapture(QtCore.QObject): #once the camera caputre is started from completion of the QML , send signal that the image capture has started started = Signal() imageReady = Signal() indexChanged = Signal() def __init__(self,parent=None): super(CVCapture, self).__init__(parent) self._image = QtGui.QImage() self._index = 0 #self.image_handler = image_handler #self.m_videoCapture = cv2.VideoCapture() self.m_timer = QtCore.QBasicTimer() #self.m_filters = [] self.m_busy = False #self.testImage = None #self.frame = None @Slot() @Slot(int) def start(self, *args): print('start the image display') if args: self.setIndex(args[0]) self.m_timer.start(50, self) self.started.emit() @Slot() def stop(self): self.m_timer.stop() def timerEvent(self, e): #print(f'image handler data is {image_handler.oneSecondCounter}') if e.timerId() != self.m_timer.timerId(): return #print('timerEvent Happening') #grabbedImage = image_handler.thumbnailImage.copy() #ret, frame = self.m_videoCapture.read() #ret = False #print(f'testimage size{testImage.shape}') if myTestClasse.image is not None: self.testImage = myTestClasse.image.copy() #print(f'thumbnail image :{self.testImage}') #self.frame = self.testImage.copy() #ret = True #cv2.imwrite('test3.png',self.testImage) else: return #if not ret: #print('timerEvent Stopping') #self.m_timer.stop() #return if self.m_busy == False: #print('start thread show image') #cv2.imwrite('test4.png',self.testImage) if self.testImage is not None: #localTest = self.testImage.copy() #print('start thread show image2') #cv2.imwrite('test4to5.png',self.testImage) #threading.Thread(target=self.process_image, args=(np.copy(self.testImage),)).start() self.process_image(self.testImage.copy()) @Slot(np.ndarray) def process_image(self, frame): #print('process image') cv2.imwrite('test5.png',frame) self.m_busy = True #print(f'flag is{self.m_busy}') #for f in self.m_filters: # frame = f.process_image(frame) image = CVCapture.ToQImage(frame) #if self._image == image: # self.m_busy = False # return self._image = image self.m_busy = False self.setImage() #QtCore.QMetaObject.invokeMethod(self,"setImage",QtCore.Qt.QueuedConnection) @staticmethod def ToQImage(im): if im is None: return QtGui.QImage() if im.dtype == np.uint8: if len(im.shape) == 2: qim = QtGui.QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QtGui.QImage.Format_Indexed8) qim.setColorTable(gray_color_table) return qim.copy() elif len(im.shape) == 3: if im.shape[2] == 3: w, h, _ = im.shape rgb_image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) flip_image = cv2.flip(rgb_image, 1) qim = QtGui.QImage(flip_image.data, h, w, QtGui.QImage.Format_RGB888) return qim.copy() return QtGui.QImage() def getImage(self): return self._image @Slot() def setImage(self): self.imageReady.emit() def index(self): return self._index def setIndex(self, index): if self._index == index: return self._index = index self.indexChanged.emit() image = Property(QtGui.QImage, fget=getImage, notify=imageReady) index = Property(int, fget=index, fset=setIndex, notify=indexChanged) """