日常写Qt相关的程序,对于某些主题,网上常能找到用C++的代码,反而Python很难找到。这时很自然会尝试将C++代码修改,以图在PyQt中运行。但是在转换过程中,除了函数名、函数参数、各个Qt对象的细节以及对Python的特定适配行为等要注意外,还要注意Python独有的特性对程序带来的影响。
先列举新建一个窗体的三种方法:1.主函数创建窗体(声明变量)2.主函数创建窗体(不声明变量)3.非主函数创建窗体(声明变量)。代码先用Python实现,后用C++实现(后面两个头文件和一个源文件),尽量保持各种调用的一致。
结果则是对于方式二和三,Python中的窗体一闪而过,但程序还在运行;C++则无论何种方式,窗体都能保持活动。程序中没有显式隐藏窗体,猜测可能是Python中的GC机制原因,在不声明式调用后和函数销栈之后,不是主函数中声明的窗体都在创建后被销毁掉了一些东西,而C++中则非强制析构都不会销毁,所以Python中的窗体才会闪退。
# test.py
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.lab = QLabel(self)
self.lab.setText("App")
self.setWindowTitle("test")
self.resize(200, 200)
def f():
w = MainWindow()
w.show()
app = QApplication(sys.argv)
# f() # 方式一
# MainWindow().show() # 方式二
w = MainWindow()
w.show()
# 方式三
app.exec()
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
#include <QLabel>
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
protected:
QLabel* lab;
void paintEvent(QPaintEvent* event) override;
};
#endif
// mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QWidget(parent)
{
this->lab = new QLabel(this);
this->lab->setText("App");
resize(200, 200);
}
void MainWindow::paintEvent(QPaintEvent* event) {}
MainWindow::~MainWindow() {}
// main.cpp
#include "mainwindow.h"
#include <QApplication>
void f()
{
MainWindow* w = new MainWindow();
w->show();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// f(); // 方式一
// (new MainWindow())->show(); // 方式二
MainWindow w;
w.show();
// 方式三
return app.exec();
}