Qt/C++和PyQt中的窗体对象存在问题

日常写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();
}

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值