对于这个问题,我指的是https://gist.github.com/zhanglongqi/78d7b5cd24f7d0c42f5d116d967923e7
中的代码上面的代码显示了如何在当前窗口小部件上绘制叠加层,这样可以正常工作。但是我想将参数传递到overlay类中,并使用这些变量来触发overlay类中的paintEvent
。
我修改了代码如下......
# -*- coding:utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class overlay(QWidget):
def __init__(self, parent=None):
super(overlay, self).__init__(parent)
palette = QPalette(self.palette())
palette.setColor(palette.Background, Qt.transparent)
self.setPalette(palette)
@pyqtSlot(int)
def getValue(self, a): # variable is received.
self.a = a
print(self.a)
self.update()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 127)))
painter.drawLine(self.width() / 8, self.height() / 8, 7 * self.width() / 8, 7 * self.height() / 8)
painter.drawLine(self.width() / 8, 7 * self.height() / 8, 7 * self.width() / 8, self.height() / 8)
painter.drawLine(self.a , self.a+50, self.a +10, self.a + 100) #Here I want to draw the line using parameter.
painter.setPen(QPen(Qt.NoPen))
class windowOverlay(QWidget):
signal = pyqtSignal(int)
def __init__(self, parent=None):
super(windowOverlay, self).__init__(parent)
self.editor = QTextEdit()
self.editor.setPlainText("OVERLAY" * 100)
self.button = QPushButton("Toggle Overlay")
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.addWidget(self.editor)
self.verticalLayout.addWidget(self.button)
self.overlay = overlay(self.editor)
self.overlay.hide()
self.button.clicked.connect(self.switch_and_send_signal)
def switch_and_send_signal(self):
if self.overlay.isVisible():
self.overlay.setVisible(False)
else:
self.overlay.setVisible(True)
self.obj = overlay()
a = 100
self.signal.connect(self.obj.getValue)
self.signal.emit(a)
self.signal.disconnect(self.obj.getValue)
def resizeEvent(self, event):
self.overlay.resize(event.size())
event.accept()
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = windowOverlay()
main.show()
sys.exit(app.exec_())
问题:
似乎传输了参数,但paintEvent
未更新。该参数未到达paintEvent
。我做错了什么?
感谢您的帮助!
答案 0 :(得分:1)
问题是由于您正在创建未连接的叠加层对象,您必须执行的操作是使用与我在下面显示的相同的对象:
class windowOverlay(QWidget):
signal = pyqtSignal(int)
def __init__(self, parent=None):
super(windowOverlay, self).__init__(parent)
self.editor = QTextEdit()
self.editor.setPlainText("OVERLAY" * 100)
self.button = QPushButton("Toggle Overlay")
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.addWidget(self.editor)
self.verticalLayout.addWidget(self.button)
self.overlay = overlay(self.editor)
self.overlay.hide()
self.signal.connect(self.overlay.getValue)
self.button.clicked.connect(self.switch_and_send_signal)
def switch_and_send_signal(self):
self.overlay.setVisible(not self.overlay.isVisible())
a = 100
self.signal.emit(a)
def resizeEvent(self, event):
self.overlay.resize(event.size())
event.accept()