我正在尝试设置一个GUI,它将在PyQt5中包含多个页面。窗口的最小尺寸为800x600,但可以自定义。我希望窗口中的大多数(但不是全部)元素能够随其缩放。我已经有一个解决方案,但是我觉得它不是很优雅。
以下是800x600窗口的示例:
这是缩放后的另一个示例
我尝试使用QVBoxLayout,但是对于该系统,我无法设法保持此处的布局(并不是说这是不可能的),而是所有小部件都变得居中且宽度相同。稍后,我可能还会考虑在与某些现有小部件的y值相同的一侧添加小部件,这是我不确定如何处理盒子布局的另一件事
以下是相关代码:
class CreatePage(QWidget):
def __init__(self, parent=None):
super().__init__()
self.initUI()
def initUI(self):
self.homeBtn = QPushButton("Home", self)
self.homeBtn.move(10, 10)
self.frontLabel = QLabel("Front", self)
self.frontLabel.setFont(QFont("Decorative", 20))
self.frontEdit = QTextEdit(self)
self.frontEdit.setFont(QFont("Decorative", 11))
self.backLabel = QLabel("Back", self)
self.backLabel.setFont(QFont("Decorative", 20))
self.backEdit = QTextEdit(self)
self.backEdit.setFont(QFont("Decorative", 11))
def paintEvent(self, e):
qp = QPainter()
qp.setFont(QFont("Decorative", 20))
size = self.size()
h = size.height()
w = size.width()
frontW = qp.fontMetrics().width("Front")
self.frontLabel.move((w/2) - (frontW/2) , h/15)
#I use fontMetrics to determine the width of the text
#I then use this information to centre the text
self.frontEdit.move(50, h/15 + 40)
self.frontEdit.resize(w-100, h/3)
backW = qp.fontMetrics().width("Back")
self.backLabel.move((w/2) - (backW/2), h/2)
self.backEdit.move(50, h/2 + 40)
self.backEdit.resize(w-100, h/3)
对于任何一般的草率表示歉意,我对PyQt和整体上的GUI编程都是陌生的。无论如何,我用于调整大小和移动小部件的公式是相当随意的。有谁知道实现此效果的更好方法?
答案 0 :(得分:0)
尝试一下:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class CreatePage(QWidget):
def __init__(self, parent=None):
super().__init__()
self.initUI()
def initUI(self):
self.homeBtn = QPushButton("Home")
self.frontLabel = QLabel("Front")
self.frontLabel.setFont(QFont("Decorative", 20))
self.frontEdit = QTextEdit(placeholderText="frontEdit")
self.frontEdit.setFont(QFont("Decorative", 11))
self.backLabel = QLabel("Back")
self.backLabel.setFont(QFont("Decorative", 20))
self.backEdit = QTextEdit(placeholderText="backEdit")
self.backEdit.setFont(QFont("Decorative", 11))
grid = QGridLayout()
grid.addWidget(self.homeBtn, 0, 0, alignment=Qt.AlignTop | Qt.AlignLeft)
grid.addWidget(self.frontLabel, 1, 0, alignment=Qt.AlignCenter)
grid.addWidget(self.frontEdit, 2, 0)
grid.addWidget(self.backLabel, 3, 0, alignment=Qt.AlignCenter)
grid.addWidget(self.backEdit, 4, 0)
self.setLayout(grid)
if __name__=="__main__":
app = QApplication(sys.argv)
myapp = CreatePage()
myapp.show()
sys.exit(app.exec_())