我正在尝试将按钮放在圆形布局中。这是我到目前为止编写的代码。
class Temp(QPushButton):
def __init__(self, x, y, w, h, parent = None):
super(Temp, self).__init__(parent)
self.w = w
self.h = h
self.x = x
self.y = y
self.text = "test"
def paintEvent(self, e):
super(self.parent, self).paintEvent(e)
qp = QPainter()
qp.begin(self.viewPort())
self.drawP(qp)
qp.end()
def drawP(self, qp):
qp.setPen(Qt.red)
qp.drawEllipse(self.x, self.y, self.w, self.h)
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 350, 100)
self.setWindowTitle('Points')
self.show()
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawP(qp)
qp.end()
def drawP(self, qp):
theta = 2 * np.pi / 15
for i in range(15):
angle = theta * (i + 1)
dx = int(round(400 + 300 * np.cos(angle)))
dy = int(round(300 + 300 * np.sin(angle)))
#qp.drawEllipse(dx, dy, 10, 10)
t = Temp(dx, dy, 10, 10, parent = self)
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
如果我在Example类中取消注释drawEllipse函数,我会在圆形布局中获取椭圆而不是按钮。
答案 0 :(得分:1)
这是一个清理过的工作版本:
class Temp(QPushButton):
def __init__(self, x, y, w, h, parent=None):
super(Temp, self).__init__(parent)
self.w = w
self.h = h
self.x = x
self.y = y
self.text = "test"
def paintEvent(self, e):
qp = QPainter(self)
qp.setPen(Qt.red)
qp.drawEllipse(0, 0, self.w - 2, self.h - 2)
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 350, 100)
self.setWindowTitle('Points')
self.drawP()
def drawP(self):
theta = 2 * np.pi / 15
for i in range(15):
angle = theta * (i + 1)
dx = int(round(400 + 300 * np.cos(angle)))
dy = int(round(300 + 300 * np.sin(angle)))
t = Temp(dx, dy, 10, 10, parent=self)
t.setGeometry(dx, dy, 10, 10)
app = QApplication(sys.argv)
ex = Example()
self.show()
sys.exit(app.exec_())
一些提示:
.show()
.show()
__init__
或initUI
答案 1 :(得分:1)
你正在混淆多个问题:
您不应该在绘画事件中添加新的小部件。应该在构造函数中将按钮添加到Example。
您应该从QPushButtons开始,让它们工作,然后才切换到您自己的类。 10x10太小而无法显示按钮!
小部件不应该显示自己。它的用户应该这样做。
按钮没有视口。
添加到已显示的窗口小部件的窗口小部件将不可见。
从这样的事情开始:
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
theta = 2 * np.pi / 15
for i in range(15):
angle = theta * (i + 1)
dx = int(round(self.width()/2 + self.width()/3 * np.cos(angle)))
dy = int(round(self.height()/2 + self.height()/3 * np.sin(angle)))
b = QPushButton("test", parent = self)
b.setGeometry(QRect(dx, dy, 50, 50))
app = QApplication(sys.argv)
ex = Example()
ex.setGeometry(300, 300, 350, 100)
ex.show()
sys.exit(app.exec_())