I have this function to center an object in the middle of the screen.
I want to center a QMainWindow, QInputDialog and a QMessageBox.
This is my MessageBox:
def _Warning(self,_type):
infoBox = QtWidgets.QMessageBox()
infoBox.setIcon(QtWidgets.QMessageBox.Warning)
infoBox.setWindowTitle("Warning")
if (_type=="File"):
infoBox.setText("The File Already exist in the current Directory")
else:
infoBox.setText("The Folder Already exist in the current Directory")
self.center(infoBox)
infoBox.exec_()
This is my QInputDialog:
def AddFile_B(self):
self.cuadro = QInputDialog()
self.center(self.cuadro)
text, okPressed = self.cuadro.getText(self, "New File","File Name:", QLineEdit.Normal, "")
if okPressed and text != '':
file = File_Node(text)
verify = self.bonsai_B.addChild(file)
if (verify == True):
item = QtWidgets.QListWidgetItem(None,0)
self.TreeB.addItem(item)
else:
del file
self._Warning("File")
This is My Center Function:
def center(self,object):
qtRectangle = object.frameGeometry()
centerPoint = QtWidgets.QDesktopWidget().availableGeometry().center()
qtRectangle.moveCenter(centerPoint)
object.move(qtRectangle.topLeft())
I can only center the QMainWindow.
The logic is to move the object into the topLeft Point (screenWidth/2 - objectWidth/2, screenHeight/2 - objectHeight/2) but I don't know what I am doing wrong.
- QMessageBox
In the case of
QMessageBox
this is resized in theexec_()
method, so a possible solution is to useQTimer.singleShot()
to change the geometry a moment after being displayed.- QInputDialog
In the case of QInputDialog, the QInputDialog::getText() method is static, so the "self.cuadro" object is not the window since the window is created within that method. If you pass a parent to getText() then by default it will be centered with respect to that.
So if the QMainWindow is centered and assuming that QMainWindow is the self then it is not necessary to modify anything.
If instead the parent is not centered on the screen then there are 2 possible solutions: