【发布时间】:2019-03-11 12:04:00
【问题描述】:
我正在尝试将 QMessageBox 小部件居中,使其中心与父小部件的中心对齐。
这只是对齐左上角:
msgBox.move(parent.pos())
我做了一些数学运算,尝试根据小部件的尺寸对齐中心。
这会将 msgBox 的左上角与父级的中心对齐:
x1 = parent.frameGeometry().width()
y1 = parent.frameGeometry().height()
#Offset msgBox by half of parent's width and height
msgBox.move(parent.pos().x() + x1/2, parent.pos().y() + y1/2)
继续,这应该对齐 msgBox 和 parent 的 x 轴,但 msgBox 偏移不正确
:
x1 = parent.frameGeometry().width()
y1 = parent.frameGeometry().height()
x2 = msgBox.frameGeometry().width()
y2 = msgBox.frameGeometry().height()
#Offset msgBox by half of parent's width and height
#Then offset msgBox back by half of its width
msgBox.move(parent.pos().x() + x1/2 - x2/2, parent.pos().y() + y1/2)
为什么这不能正常工作,正确的解决方案是什么?谢谢!
编辑:
这是我的程序的简化版本,它给出了相同的结果:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Ui_Form(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setupUi(self)
def infoBox(self):
#Create Info box
infoBox = QtWidgets.QMessageBox()
infoBox.setIcon(QtWidgets.QMessageBox.Warning)
infoBox.setText("Warning:")
message = "Blank entries indicate no corresponding Misc word and will be omitted from the output file."
message += "\n\nConvert anyway?"
infoBox.setInformativeText(message)
infoBox.setWindowTitle("Warning")
infoBox.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
#Position infoBox
infoBox.move(self.rect().center())
#Execute infoBox
reply = infoBox.exec_()
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 400)
self.main_Layout = QtWidgets.QVBoxLayout(Form)
self.main_Layout.setObjectName("main_Layout")
#Add b utton
self.button = QtWidgets.QPushButton(Form)
font = QtGui.QFont()
font.setPointSize(10)
self.button.setFont(font)
self.button.setObjectName("saveDefault")
self.main_Layout.addWidget(self.button)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Test"))
self.button.setText(_translate("Form", "Warning"))
self.button.clicked.connect(self.infoBox)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_Form()
ex.show()
sys.exit(app.exec_())
【问题讨论】:
-
只有在我扔的时候。