pyqt4 mousePressEvent 未调用(没有小部件?)
我刚刚写了一个小例子,但无法让它运行。
from PyQt4 import QtGui, QtCore
import sys
class Drawer(QtGui.QWidget):
def __init__(self, parent=None):
super(Drawer, self).__init__(parent)
self.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(99, 0, 0).name())
def mousePressEvent(self, event):
print 'mouse pressed'
self.update();
class MyApp(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.drawer = Drawer(self)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
myapp = MyApp()
myapp.show()
sys.exit(app.exec_())
小部件未显示(无颜色,窗口为灰色),如果我按下鼠标则不打印..
我的错误在哪里?
已解决:qiao只需在评论中指出我,我的错误是添加qt4 场景图中的小部件。我想我必须在 init 中调用父级,仅此而已。这还不够,我必须添加一个 QLayout 并在其中添加子级(这很明显:方法 addWidget 仅在 QLayout 中编写,而不是在 QWidget 中编写,并且具有场景图形系统,不可能添加新孩子是很奇怪的)
I have just wrote a little example and i can't manage to make it run.
from PyQt4 import QtGui, QtCore
import sys
class Drawer(QtGui.QWidget):
def __init__(self, parent=None):
super(Drawer, self).__init__(parent)
self.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(99, 0, 0).name())
def mousePressEvent(self, event):
print 'mouse pressed'
self.update();
class MyApp(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.drawer = Drawer(self)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
myapp = MyApp()
myapp.show()
sys.exit(app.exec_())
widget is not shown (no color, the window is gray) and if i press the mouse no print..
where is my error?
SOLVED: as qiao just point me in a comment, my error is the way to add a widget in the qt4 kind of scenegraph. i thought i had to call the parent in init and that's all. This is not enogh, i have to add a QLayout and add the childs in it (this is quite obvious: the method addWidget is written only in QLayout and not in QWidget and having a scenegraph system without the possibility of adding new child is quite weird)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将主窗口的中央小部件设置为抽屉。否则抽屉将不会连接到主窗口。
经过上述修复后,您将看到鼠标按下事件正常工作。
至于颜色,设置QMainWindow的样式表就可以了,将Drawer设置为另一个小部件(如QLineEdit)也可以。我不知道这是怎么回事。
You have to set the central widget of the main window to be the drawer. Otherwise the drawer will not attached to the main window.
After the above fix, you will see mouse press event working properly.
As for the color, setting the stylesheet of QMainWindow is fine, so is setting Drawer to be another widget(like QLineEdit). I don't know what's the matter here.