作者:虚坏叔叔
早餐店不会开到晚上,想吃的人早就来了!😄
c++读取python的配置项改变窗口大小和标题
一、c++读取python的配置项改变窗口大小
python中的pyqt.py
模块定义配置项
print("Python PyPlayer")
conf = {
"width" : 1280,
"height" : 720,
"title" : "PyPlaye播放器"
}
#主函数 在子线程中调用,线程是c++创建
def main():
print("Python main")
这里为了防止编码问题,用vscode打开编辑
在C++代码PyPlyer.cpp
中获取python配置项
#include <Python.h>
#include "PyPlayer.h"
#include <iostream>
using namespace std;
static PyObject *pModule = 0;
PyPlayer::PyPlayer(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
Py_SetPythonHome(L"./");
Py_Initialize();
// 载入模块
pModule = PyImport_ImportModule("pyqt");
if (!pModule)
{
printf("PyImport import error");
PyErr_Print();
return;
}
// 获取python配置项 改变窗口的大小和标题
PyObject *conf = PyObject_GetAttrString(pModule, "conf");
if (!conf)
{
cout << "Please set the conf" << endl;
PyErr_Print();
return;
}
PyObject *key = PyUnicode_FromString("width");
int width = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
key = PyUnicode_FromString("height");
int height = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
if (width > 0 && height > 0)
{
resize(width, height);
}
Py_XDECREF(conf);
// 开启线程 调用python的 main函数
}
运行:
可以看到窗口大小被成功修改了
二、c++读取python的配置项改变窗口标题
c++
端添加python
标题的读取:
#include <Python.h>
#include "PyPlayer.h"
#include <iostream>
using namespace std;
static PyObject *pModule = 0;
PyPlayer::PyPlayer(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
Py_SetPythonHome(L"./");
Py_Initialize();
// 载入模块
pModule = PyImport_ImportModule("pyqt");
if (!pModule)
{
printf("PyImport import error");
PyErr_Print();
return;
}
// 获取python配置项 改变窗口的大小和标题
PyObject *conf = PyObject_GetAttrString(pModule, "conf");
if (!conf)
{
cout << "Please set the conf" << endl;
PyErr_Print();
return;
}
PyObject *key = PyUnicode_FromString("width");
int width = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
key = PyUnicode_FromString("height");
int height = PyLong_AsLong(PyDict_GetItem(conf, key));
Py_XDECREF(key);
// 改变窗口标题
key = PyUnicode_FromString("title");
wchar_t title[1024] = { 0 };
PyUnicode_AsWideChar(PyDict_GetItem(conf, key), title, 1023);
this->setWindowTitle(QString::fromUtf16((char16_t*)title));
Py_XDECREF(key);
if (width > 0 && height > 0)
{
resize(width, height);
}
Py_XDECREF(conf);
// 开启线程 调用python的 main函数
}
运行可以看到成功修改了qt对话框
的标题
三、总结
- 本文介绍了c++读取python的配置项改变窗口大小和标题 。