7

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

12

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()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
1

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())
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 02 '22 at 12:29