Module 'PyQt6.QtWidgets' has no attribute 'QDesktopWidget'

Viewed 2069

I try to run this code, but it always get this AttributeError, I have searched for many website but there wasn't any answer.

QtWidgets.QDesktopWidget().availableGeometry().center()
AttributeError: module 'PyQt6.QtWidgets' has no attribute 'QDesktopWidget'

My Code:

from PyQt6 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def center(self):
        qr = Form.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

I'm using PyQt6 Version 6.1.0, Python 3.9.5

2 Answers

From the docs:

QDesktopWidget and QApplication::desktop()
QDesktopWidget was already deprecated in Qt 5, and has been removed in Qt 6, together with QApplication::desktop().

QScreen provides equivalent functionality to query for information about available screens, screen that form a virtual desktop, and screen geometries.

Use QWidget::setScreen() to create a QWidget on a specific display; note that this does not move a widget to a screen in a virtual desktop setup.

Then use:

cp = QtGui.QGuiApplication.primaryScreen().availableGeometry().center()

You can try this

from PyQt6 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def center(self):
        qr=self.frameGeometry()           
        cp=QtGui.QGuiApplication.primaryScreen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
Related