Python PyQt5中QWidget的叠加
我不知道为什么,但当我在QXBoxLayout(两个小部件)中使用我的两个自定义小部件(SquareCalc、LinePaint)时,它们彼此重叠 我将Python3.5.2与PyQt5一起使用 这是我的代码:Python PyQt5中QWidget的叠加,python,pyqt5,Python,Pyqt5,我不知道为什么,但当我在QXBoxLayout(两个小部件)中使用我的两个自定义小部件(SquareCalc、LinePaint)时,它们彼此重叠 我将Python3.5.2与PyQt5一起使用 这是我的代码: import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor, QPainter, QPen from PyQt5.QtWidgets import (QApplication, QWidget,
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QPainter, QPen
from PyQt5.QtWidgets import (QApplication, QWidget,
QGridLayout, QVBoxLayout, QHBoxLayout,QLabel, QLineEdit, QPushButton)
class SquareCalc(QWidget):
def __init__(self):
super().__init__()
def initUI(self):
self.setGeometry(0,0,100,100)
self.inputLine = QLineEdit()
self.outputLine = QLineEdit()
self.outputLine.setReadOnly(True)
self.inputLine.returnPressed.connect(self.calc)
self.calcButton = QPushButton("&Calc")
self.calcButton.clicked.connect(self.calc)
lineLayout = QGridLayout()
lineLayout.addWidget(QLabel("num"), 0, 0)
lineLayout.addWidget(self.inputLine, 0, 1)
lineLayout.addWidget(QLabel("result"), 1, 0)
lineLayout.addWidget(self.outputLine, 1, 1)
buttonLayout = QHBoxLayout()
buttonLayout.addWidget(self.calcButton)
mainLayout = QVBoxLayout()
mainLayout.addLayout(lineLayout)
mainLayout.addLayout(buttonLayout)
self.setLayout(mainLayout)
def calc(self):
n = int(self.inputLine.text())
r = n**2
self.outputLine.setText(str(r))
class LinePainting(QWidget):
def __init__(self):
super().__init__()
def initPainting(self):
self.setGeometry(0, 0, 300, 300)
self.setWindowTitle('Pen styles')
mainLayout = QVBoxLayout()
mainLayout.addWidget(self)
self.show()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawLines(qp)
qp.end()
def drawLines(self, qp):
pen = QPen(Qt.black, 2, Qt.SolidLine)
qp.setPen(pen)
qp.drawLine(20, 40, 250, 40)
pen.setStyle(Qt.DashLine)
qp.setPen(pen)
qp.drawLine(20, 80, 250, 80)
pen.setStyle(Qt.DashDotLine)
qp.setPen(pen)
qp.drawLine(20, 120, 250, 120)
pen.setStyle(Qt.DotLine)
qp.setPen(pen)
qp.drawLine(20, 160, 250, 160)
pen.setStyle(Qt.DashDotDotLine)
qp.setPen(pen)
qp.drawLine(20, 200, 250, 200)
pen.setStyle(Qt.CustomDashLine)
pen.setDashPattern([1, 4, 5, 4])
qp.setPen(pen)
qp.drawLine(20, 240, 250, 240)
class twoWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.widget1 = SquareCalc()
self.widget2 = LinePainting()
mainLayout = QHBoxLayout()
mainLayout.addWidget(self.widget1)
mainLayout.addWidget(self.widget2)
self.setLayout(mainLayout)
self.setWindowTitle("Mix line/factorial")
self.widget2.initPainting()
self.widget1.initUI()
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = twoWidget()
main_window.setStyleSheet(open("lol.qss", "r").read())
main_window.show()
sys.exit(app.exec_())
我发现了问题,我只需要在我的小部件SquareCalc上放一个固定的大小, 加上
self.setFixedSize(sizeX,sizeY)
代替:
self.setGeometry(0, 0, 300, 300)
只是因为QPainter不需要最小大小,相反,QLineEdit()和QPushButton(),是的