在PySide2中如何重新实现QWidget :: nativeEvent

时间:2018-12-06 03:17:43

标签: python qt winapi pyside2

PySide2 Documentation中所述,PySide2.QtWidgets.QWidget没有虚函数nativeEvent,该虚函数在Ct的Qt5中可用且可重新实现。我试图重新实现它,但从未调用过它。一个测试示例如下:

import sys
from PySide2.QtCore import QObject, QSize
from PySide2.QtWidgets import QApplication, QWidget

class MainWidget(QWidget):
    def __init__(self):
        super().__init__()
    def sizeHint(self):
        return QSize(400,300)
    def enterEvent(self, event):
        print("enterEvent") # this log is printed when mouse enters
        return super().enterEvent(event)
    def leaveEvent(self, event):
        print("leaveEvent") # this log is printed when mouse leaves
        return super().leaveEvent(event)
    def nativeEvent(self, eventType, message, result):
        print("nativeEvent") # never see this log
        return super().nativeEvent(eventType, message, result)

if __name__ == "__main__":
    app = QApplication()
    widget = MainWidget()
    widget.show()
    sys.exit(app.exec_())

在C ++中,我可以观察到许多nativeEvent的调用:

### MainWidget.h ###

#pragma once
#include <QWidget>
class MainWidget : public QWidget
{
  Q_OBJECT
public:
  MainWidget(QWidget *parent = Q_NULLPTR) : QWidget(parent) {}
  QSize sizeHint();
protected:
  bool nativeEvent(const QByteArray &eventType, void *message, long *result);
};

### MainWidget.cpp ###

#include "MainWidget.h"
QSize MainWidget::sizeHint()
{
  return QSize(400, 300);
}
bool MainWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
  printf("nativeEvent\n"); // this is printed many times at the beginning of the application
  return QWidget::nativeEvent(eventType, message, result);
}

### main.cpp ###

#include <QtWidgets/QApplication>
#include <Windows.h>
#include "MainWidget.h"
int main(int argc, char *argv[])
{
  AllocConsole();
  freopen("CONOUT$", "w", stdout);
  printf("Start..");
  QApplication a(argc, argv);
  MainWidget w;
  w.show();
  return a.exec();
}

有什么方法可以在PySide2中重新实现nativeEvent方法吗?还是处理Windows消息?

0 个答案:

没有答案