如何解决PyQt在现有控件之前动态添加控件
我要存档的是创建一个(pixmap-)小部件,然后在主窗口小部件前可见。稍后,该小部件应该跟随鼠标。
所以我的主要问题是在按下空格键时动态创建一个窗口小部件,然后在其他窗口小部件前面可见该窗口小部件,而没有创建单独的窗口。
import sys
from PyQt5 import QtCore,QtGui,QtWidgets,uic
from PyQt5.QtCore import Qt
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.label = QtWidgets.QLabel()
canvas = QtGui.QPixmap(1200,800)
canvas.fill(QtGui.QColor('#ffffff')) # Fill entire canvas.
self.label.setPixmap(canvas)
self.setCentralWidget(self.label)
self.last_x,self.last_y = None,None
def mouseMoveEvent(self,e):
if self.last_x is None: # First event.
self.last_x = e.x()
self.last_y = e.y()
return # Ignore the first time.
painter = QtGui.QPainter(self.label.pixmap())
painter.drawLine(self.last_x,self.last_y,e.x(),e.y())
painter.end()
self.update()
# Update the origin for next time.
self.last_x = e.x()
self.last_y = e.y()
def mouseReleaseEvent(self,e):
self.last_x = None
self.last_y = None
def keyPressEvent(self,QKeyEvent):
if QKeyEvent.key() == Qt.Key_Space:
block = QtGui.QPixmap(20,20)
block.fill(QtGui.QColor('blue'))
self.image = QtWidgets.QLabel()
self.image.setPixmap(block)
self.image.move(20,20)
# self.image.raise_()
# self.image.show()
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
如果我要在图像上调用.show(),则会打开一个带有此小部件的单独窗口。但这不是我要存档的内容。 _raise似乎什么都没做。
编辑:我可以通过使用QStackedLayout来实现吗?
解决方法
没有父级的窗口小部件将显示为窗口,因此解决方案是将其传递给父级并调用show()方法以显示它:
def keyPressEvent(self,QKeyEvent):
if QKeyEvent.key() == Qt.Key_Space:
block = QtGui.QPixmap(20,20)
block.fill(QtGui.QColor('blue'))
self.image = QtWidgets.QLabel(self.label)
self.image.setPixmap(block)
self.image.move(20,20)
self.image.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。