I have saved an image in sqlite and i am trying to retrieve it and displaying it in a QLabel using this code.
connect(ui.tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
this, SLOT(getImage(QModelIndex,QModelIndex)));
void smith::getImage()
{
.......
QModelIndex index = ui.tableView->currentIndex();
QString sqlQuery = QString("SELECT image FROM %1 WHERE id=:id").arg(tableName);
query.prepare(sqlQuery);
QSqlRecord recordz = tableModel->record(index.row());
query.bindValue(":id", recordz.value("id").toInt());
query.exec();
tableModel->select();
QByteArray array = query.value(0).toByteArray();
QBuffer buffer(&array);
buffer.open( QIODevice::ReadOnly );
QImageReader reader(&buffer, "PNG");
QImage image = reader.read();
if( image.isNull() )
{
QMessageBox::about(this, tr("Image Is Null"),
tr("<h2>Image Error</h2>"
"<p>Copyright © 2011."
"<p>Message Box To Check For "
" Errors "
));
}
ui.imageLabel->setPixmap( QPixmap::fromImage(image));
}
The project compiles without any errors but the image won't show.
I'd suggest adding some error-checking to your code, to narrow down where the error occurs.
For example, the documentation for QImageReader::read() says that if the image can't be read, the resultant image is null, and it tells you how to find out what the error was.
So after your call to reader.read(), check image.isNull().
And earlier on, check array.size() to make sure that you really got a value back from the database.
And the check the result returned by buffer.open( QIODevice::ReadOnly ) - the docs say it will return false if the call failed.
Related
I have integrated the NDI SDK from NewTek in the current version 5 into my Qt6.3 widget project.
I copied and included the required DLLs and header files from the NDI SDK installation directory into my project.
To test my build environment I tried to compile a simple test program based on the example from "..\NDI 5 SDK\Examples\C++\NDIlib_Recv".
That was also successful.
I was therefore able to receive or access data from my NDI source.
There is therefore a valid frame in the video_frame of the type NDIlib_video_frame_v2_t. Within the structure I can also query correct data of the frame such as the size (.xres and .yres).
The pointer p_data points to the actual data.
So far so good.
Of course, I now want to display this frame on the Qt6 GUI. In other words, the only thing missing now is the conversion into an appropriate format so that I can display the frame with QImage, QPixmap, QLabel, etc.
But how?
So far I've tried calls like this:
curFrame = QImage(video_frame.p_data, video_frame.xres, video_frame.yres, QImage::Format::Format_RGB888);
curFrame.save("out.jpg");
I'm not sure if the format is correct either.
Here's a closer look at the mentioned frame structure within the Qt debug session:
my NDI video frame in the Qt Debug session, after receiving
Within "video_frame" you can see the specification video_type_UYVY.
This may really be the format as it appears at the source!?
Fine, but how do I get this converted now?
Many thanks and best regards
You mean something like this? :)
https://github.com/NightVsKnight/QtNdiMonitorCapture
Specifically:
https://github.com/NightVsKnight/QtNdiMonitorCapture/blob/main/lib/ndireceiverworker.cpp
Assuming you connect using NDIlib_recv_color_format_best:
NDIlib_recv_create_v3_t recv_desc;
recv_desc.p_ndi_recv_name = "QtNdiMonitorCapture";
recv_desc.source_to_connect_to = ...;
recv_desc.color_format = NDIlib_recv_color_format_best;
recv_desc.bandwidth = NDIlib_recv_bandwidth_highest;
recv_desc.allow_video_fields = true;
pNdiRecv = NDIlib_recv_create_v3(&recv_desc);
Then when you receive a NDIlib_video_frame_v2_t:
void NdiReceiverWorker::processVideo(
NDIlib_video_frame_v2_t *pNdiVideoFrame,
QList<QVideoSink*> *videoSinks)
{
auto ndiWidth = pNdiVideoFrame->xres;
auto ndiHeight = pNdiVideoFrame->yres;
auto ndiLineStrideInBytes = pNdiVideoFrame->line_stride_in_bytes;
auto ndiPixelFormat = pNdiVideoFrame->FourCC;
auto pixelFormat = NdiWrapper::ndiPixelFormatToPixelFormat(ndiPixelFormat);
if (pixelFormat == QVideoFrameFormat::PixelFormat::Format_Invalid)
{
qDebug().nospace() << "Unsupported pNdiVideoFrame->FourCC " << NdiWrapper::ndiFourCCToString(ndiPixelFormat) << "; return;";
return;
}
QSize videoFrameSize(ndiWidth, ndiHeight);
QVideoFrameFormat videoFrameFormat(videoFrameSize, pixelFormat);
QVideoFrame videoFrame(videoFrameFormat);
if (!videoFrame.map(QVideoFrame::WriteOnly))
{
qWarning() << "videoFrame.map(QVideoFrame::WriteOnly) failed; return;";
return;
}
auto pDstY = videoFrame.bits(0);
auto pSrcY = pNdiVideoFrame->p_data;
auto pDstUV = videoFrame.bits(1);
auto pSrcUV = pSrcY + (ndiLineStrideInBytes * ndiHeight);
for (int line = 0; line < ndiHeight; ++line)
{
memcpy(pDstY, pSrcY, ndiLineStrideInBytes);
pDstY += ndiLineStrideInBytes;
pSrcY += ndiLineStrideInBytes;
if (pDstUV)
{
// For now QVideoFrameFormat/QVideoFrame does not support P216. :(
// I have started the conversation to have it added, but that may take awhile. :(
// Until then, copying only every other UV line is a cheap way to downsample P216's 4:2:2 to P016's 4:2:0 chroma sampling.
// There are still a few visible artifacts on the screen, but it is passable.
if (line % 2)
{
memcpy(pDstUV, pSrcUV, ndiLineStrideInBytes);
pDstUV += ndiLineStrideInBytes;
}
pSrcUV += ndiLineStrideInBytes;
}
}
videoFrame.unmap();
foreach(QVideoSink *videoSink, *videoSinks)
{
videoSink->setVideoFrame(videoFrame);
}
}
QVideoFrameFormat::PixelFormat NdiWrapper::ndiPixelFormatToPixelFormat(enum NDIlib_FourCC_video_type_e ndiFourCC)
{
switch(ndiFourCC)
{
case NDIlib_FourCC_video_type_UYVY:
return QVideoFrameFormat::PixelFormat::Format_UYVY;
case NDIlib_FourCC_video_type_UYVA:
return QVideoFrameFormat::PixelFormat::Format_UYVY;
break;
// Result when requesting NDIlib_recv_color_format_best
case NDIlib_FourCC_video_type_P216:
return QVideoFrameFormat::PixelFormat::Format_P016;
//case NDIlib_FourCC_video_type_PA16:
// return QVideoFrameFormat::PixelFormat::?;
case NDIlib_FourCC_video_type_YV12:
return QVideoFrameFormat::PixelFormat::Format_YV12;
//case NDIlib_FourCC_video_type_I420:
// return QVideoFrameFormat::PixelFormat::?
case NDIlib_FourCC_video_type_NV12:
return QVideoFrameFormat::PixelFormat::Format_NV12;
case NDIlib_FourCC_video_type_BGRA:
return QVideoFrameFormat::PixelFormat::Format_BGRA8888;
case NDIlib_FourCC_video_type_BGRX:
return QVideoFrameFormat::PixelFormat::Format_BGRX8888;
case NDIlib_FourCC_video_type_RGBA:
return QVideoFrameFormat::PixelFormat::Format_RGBA8888;
case NDIlib_FourCC_video_type_RGBX:
return QVideoFrameFormat::PixelFormat::Format_RGBX8888;
default:
return QVideoFrameFormat::PixelFormat::Format_Invalid;
}
}
I am making a library management software using Qt and Sqlite3.
constructor:
db = QSqlDatabase :: addDatabase("QSQLITE");
model = new QSqlTableModel(this, db);
db.setDatabaseName(":/lib/libre coupe.db");
db.setHostName("Libre Coupe");
if(db.open())
{
QSqlQuery query(db);
if (! query.exec("CREATE TABLE IF NOT EXISTS books (NAME VARCHAR(100) NOT NULL, AUTHOR VARCHAR(100) NOT NULL, UID VARCHAR(100) NOT NULL) "))
{
QMessageBox::information(this, "title", "Unable to use Sqlite");
}
if(query.lastError().text() != " ")
QMessageBox::critical(this, "Oops", query.lastError().text());
model->setTable("books");
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("Name") );
model->setHeaderData(1, Qt::Horizontal, tr("Author") );
model->setHeaderData(2, Qt::Horizontal, tr("Uid") );
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
if(!query.exec("SELECT * FROM books;"))
QMessageBox::critical(this, "Oops", query.lastError().text());
int i = 0;
while(query.next())
{
model->setData(model->index(i, 0), query.value(query.record().indexOf("NAME")));
model->setData(model->index(i, 1), query.value(query.record().indexOf("AUTHOR")));
model->setData(model->index(i, 2), query.value(query.record().indexOf("UID")));
++i;
}
}
else
QMessageBox::critical(this, "Oops!", "Could not open the database");\
I faced a problem that the database was not created automatically. So, i created it manually and added it to my resource so that it exists on every computer which uses my application.
I ran my app and went to the directory containing "libre coupe.db". There using the terminal, i found out that no table was created. I see no error message. My other functions like save don't work too while the same commands typed directly into Sqlite using terminal works as expected.
I even used the debugger and found that the program does enter the if condition i.e. the database opens successfully.
I used the following command to check if the table existed:
sqlite3 "libre coupe.db"
.tables
First line:
db.setDatabaseName(":/lib/libre coupe.db");
the starting ":" means you are trying to access an embedded binary resource using Qt's resource system.
However, SQLite databases cannot be stored in the Qt resource system. If your database is instead located at /lib/libre coupe.db, you should remove the colon at the beginning.
I have the following code (of a rich text editor written in QT 4.8) on which I'm working on:
bool TextEdit::fileSaveAs()
{
QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."),
QString(), tr("ODT document (*.odt);;HTML-Files (*.htm *.html)"), 0, QFileDialog::DontUseNativeDialog );
if (fn.isEmpty())
return false;
if (! fn.endsWith(".txt", Qt::CaseInsensitive) || (fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) )
fn += ".odt"; // default
setCurrentFileName(fn);
return fileSave();
}
The save dialog window allows to choose between *.odt and *.html extensions; however, by default, is always set the *.odt extension (see fn += ".odt").
I know that I can change this one to html, but I aim to get rid of the forced extension set inside the code and let the document to be saved with the extension selected in the save dialog window:
(source: funkyimg.com)
How can I accomplish this? Can someone suggest me some practical example, considering that I am a newbie about coding?
Use another constructor with selectedfilter argument, the result would be
QString selectedFilter;
QString fn = QFileDialog::getSaveFileName
(this,
tr("Save as..."),
QString(),
tr("ODT document (*.odt);;HTML-Files (*.htm *.html)"),
0,
QFileDialog::DontUseNativeDialog,
&selectedFilter);
I'm trying to get the row count of a QSqlQuery, the database driver is qsqlite
bool Database::runSQL(QSqlQueryModel *model, const QString & q)
{
Q_ASSERT (model);
model->setQuery(QSqlQuery(q, my_db));
rowCount = model->query().size();
return my_db.lastError().isValid();
}
The query here is a select query, but I still get -1;
If I use model->rowCount() I get only ones that got displayed, e.g 256, but select count(*) returns 120k results.
What's wrong about it?
This row count code extract works for SQLite3 based tables as well as handles the "fetchMore" issue associated with certain SQLite versions.
QSqlQuery query( m_database );
query.prepare( QString( "SELECT * FROM MyDatabaseTable WHERE SampleNumber = ?;"));
query.addBindValue( _sample_number );
bool table_ok = query.exec();
if ( !table_ok )
{
DATABASETHREAD_REPORT_ERROR( "Error from MyDataBaseTable", query.lastError() );
}
else
{
// only way to get a row count, size function does not work for SQLite3
query.last();
int row_count = query.at() + 1;
qDebug() << "getNoteCounts = " << row_count;
}
The documentation says:
Returns ... -1 if the size cannot be determined or if the database does not support reporting information about query sizes.
SQLite indeed does not support this.
Please note that caching 120k records is not very efficient (nobody will look at all those); you should somehow filter them to get the result down to a manageable size.
My english is not very good but i’ll try to describe my problem.
So, i have primitive code:
base = QSqlDatabase::addDatabase("QODBC");
QSettings sets("FlowModel","Settings");
currentBase = sets.value("currentBase").toString();
base.setHostName("localhost");
base.setDatabaseName(QString("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=%1").arg(currentBase));
if(base.open())
QMessageBox::information(0,"Все отлично!","База данных открыта","Ок");
else
QMessageBox::information(0,"Все не ахти!",base.lastError().text(),"Ок");
QSqlQuery queryMaterials("SELECT * FROM Материал",base);
int fieldNo = queryMaterials.record().indexOf("Название");
int i = 0;
while (queryMaterials.next()) {
comboBox->insertItem(i++,queryMaterials.value(fieldNo).toString());
}
queryMaterials.clear();
It works correctly and combo box takes all materials from Database;
But next is going this code:
QSqlQuery queryInfo("SELECT * FROM Свойства_материала WHERE Название='Вода'",base);
fieldNo = queryInfo.record().indexOf("P");
pLine->setText(queryInfo.value(fieldNo).toString());
And it didn’t work! Query returns an empty string (”“), but must be a number. I test this SQL-query in Access and there it works correct. Please help to understand what a problem i have.
Thank you.
P.S. I’m tried to use QSqlQuery::lastError().text() method, but it report me nothing.
I can’t understand what is that… Because this table can be opened by this code:
QSqlDatabase accessBase = QSqlDatabase::addDatabase("QODBC");
accessBase.setHostName("localhost");
accessBase.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=D:/ИТ.mdb");
if(accessBase.open())
QMessageBox::information(0,"Все отлично!","База данных открыта","Ок");
else
QMessageBox::information(0,"Все не ахти!",accessBase.lastError().text(),"Ок");
QTableView tableGhost;
QSqlTableModel tableDB;
QString whtpn = QInputDialog::getText(0, "Какую таблицу открыть?",
"Какую таблицу открыть?");
tableDB.setTable(whtpn);
tableDB.select();
tableDB.setEditStrategy(QSqlTableModel::OnFieldChange);
tableGhost.setModel(&tableDB);
tableGhost.show();
And all ok. But by query no(
Problem has been solved.
Before line
pLine->setText(queryInfo.value(fieldNo).toString());
Had to use method QSqlQuery::next();