将从Python接收到的原始字节图像数据转换为C++ Qt QIcon以在QStandardItem中显示

问题描述 投票:0回答:1

我正在创建小型 GUI 系统,我想从 Python 代码中获取原始字节形式的图像,然后使用这些原始字节创建 QImage/QIcon。对于 C++/Python 交互,我使用 Boost Python。

在 Python 代码端,我打印了原始字节: b'\x89PNG \x1a \x00\x00\x00 IHDR\x00\x00\x00@\x00\x00\x00@\x08\x02\x00\x00\x00%\x0b\xe6\x89\x00\x00\x00\x03sBIT\x08\x08\x08\xdb\xe1O \xe0\x00\x00\x00 pHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x06\xabIDATh\x81\xed\x9aOh\x13O\ x14\xc7wv\x93\xdd\xfcQ1\xa9\x8d....

我将它们作为字符串从 python 发送到 C++ 代码,例如:

data.rawBytes = str(thumbnail._raw_bytes)

在 C++ 方面,我以字符串形式提取这些字节:

std::string rawBytes = boost::python::extract<std::string>(obj.attr("rawBytes"));

上述 C++ 端收到的 rawBytes 与上面的 python 打印相同。

现在在 UI 代码中,我尝试使用这些原始字节来创建 QIcon,例如:

std::string rawbytes = data.rawBytes;
QByteArray arr();
arr.append(rawbytes.c_str(), rawbytes.length());
bool flag = pixmap.loadFromData(arr, "PNG");

QStandardItem* item = new QStandardItem(name);
item->setIcon(QIcon(pixmap));

图标没有显示在 UI 中,而且从 pixmap.loadFromData 返回的“flag”为 false,这意味着原始字节的转换存在问题。有人能指出是否需要某种从 python 到 c++ 代码的转换才能在 UI 上正确呈现此图像吗?

python c++ python-3.x qt
1个回答
0
投票

假设在Python方面你有

data.rawBytes = thumbnail._raw_bytes

没有

str
包装器和 C++ 变量
obj
引用
data
,您可以像这样使用 Python Buffer 协议:

Py_Buffer view = {0};
int ret = PyObject_GetBuffer(obj.attr("rawBytes").ptr(), &view, PyBUF_SIMPLE);
if (ret == -1) {
  // handle error
}

QByteArray arr =
  QByteArray::fromRawData(reinterpret_cast<const char *>(view.buf), view.len);
// do stuff with arr

PyObject_ReleaseBuffer(&view);
© www.soinside.com 2019 - 2024. All rights reserved.