如何使内部带有文本的透明椭圆形或替换为文本的椭圆形边框?
替换带有边框的文本
ellipse = QPainter(self)
ellipse.setOpacity(0.6)
ellipse.setPen(QtGui.QPen(Qt.darkGreen, 4, Qt.DashLine)) # Any way to replace 'DashLine with Text ?'
ellipse.setBrush(QBrush(QColor(self.window_bg), Qt.SolidPattern))
ellipse.drawEllipse(0, 0, self.ellipse_width, self.ellipse_height)
椭圆内的文本
ellipse = QPainter(self)
ellipse.setOpacity(0.6)
ellipse.setBrush(QBrush(QColor('#000000'), Qt.SolidPattern))
ellipse.drawEllipse(0, 0, 300, 300)
ellipse.drawText(10, 10, 'Random Text')
答案 0 :(得分:2)
您必须使用setClipPath()
:
import random
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def paintEvent(self, event):
window_bg = "#0011ff"
ellipse_width, ellipse_height = self.width(), self.height()
r = QtCore.QRectF(0, 0, ellipse_width, ellipse_height)
text = "Stack OverFlow :-)"
path = QtGui.QPainterPath()
path.addEllipse(r)
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setClipPath(path, QtCore.Qt.IntersectClip)
painter.setOpacity(0.6)
painter.setBrush(QtGui.QBrush(QtGui.QColor('#000000'), QtCore.Qt.SolidPattern))
painter.setPen(QtGui.QPen(QtCore.Qt.darkGreen, 4, QtCore.Qt.DashLine))
painter.setBrush(QtGui.QBrush(QtGui.QColor(window_bg), QtCore.Qt.SolidPattern))
painter.drawEllipse(r)
# draw text in random positions
for i in range(100):
x = random.randint(0, self.width())
y = random.randint(0, self.height())
painter.drawText(x, y, text)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())