【问题标题】:Qt5 call a function in a Python scriptQt5 在 Python 脚本中调用函数
【发布时间】:2025-12-08 22:30:01
【问题描述】:

我有一个带有按钮和文本字段的简单 Qt5 项目,我还在项目中创建了一个 py 文件来检查如何从 Qt 调用 python 文件中的函数。

虽然现在我被困住了;我有我的 testcpp.h 和 testcpp.cpp,我在其中定义了一个字符串和一个打印该字符串的函数;虽然我不确定现在如何调用 python 文件中的函数,它只是打印一个字符串。

我想调用Qt函数,让它调用python文件中的函数;你是怎么做到的?

testcpp.h 文件:

#ifndef TESTCPP_H
#define TESTCPP_H

#include <QObject>
#include <QString>

class testcpp : public QObject
{
    Q_OBJECT
public:
    explicit testcpp(QObject *parent = nullptr);

    QString getTest_to_print() const;
    void setTest_to_print(const QString &value);

signals:

public slots:

private:
    QString test_to_print;

};

#endif // TESTCPP_H

testcpp.cpp 文件:

#include "testcpp.h"

testcpp::testcpp(QObject *parent) : QObject(parent)
{

}

QString testcpp::getTest_to_print() const
{
    return test_to_print;
}

void testcpp::setTest_to_print(const QString &value)
{
    test_to_print = value;
}

void testcpp::PrintViaPython(QString &test_to_print)
{



}

Python 文件:

# -*- coding: utf-8 -*-

try:
    from PySide import QtWidgets
except:
    from PyQt5 import QtWidgets


class test_python:
    def __init__(self):


    def testme(self, string_to_print):
        print(string_to_print)

【问题讨论】:

  • 现货;所以我需要一个库来使用python。有趣的是,当我创建一个新文件时,python 是其中一种选择;虽然不知道为什么,因为我需要一个外部库来使用 python 文件。感谢您的提示!
  • 我认为您的意思是 Qt Creator,您可以在 IDE 中创建文件并不意味着您可以在应用程序中运行它,该库可以满足您的需求。
  • 非常感谢;确实 IDE 是 QT Creator。在这一点上,我确实错误地假设,如果 IDE 创建一个文件类型,它也支持它:) 如果您将其添加为响应,我可以将其标记为解决方案。
  • 我已经回复了,请标记为正确。

标签: python qt qt5


【解决方案1】:

任何 IDE 都可以创建任何类型的文件,但这并不意味着它可以执行,QtCreator 就是这种情况。

回答问题的背景我建议使用PythonQt库,您可以通过SIP和python.h库从头开始,但如果有我建议的库,则没有必要。

【讨论】:

  • 顺便说一句,构建 PythonQt 有什么问题吗?在运行build all 时,在 __locale 中,我在 OSX 10.11 上遇到大量编译错误。
  • 我在linux下编译过,其他操作系统没有编译过。