How to use M.S access in Qt? - c++

I want use access database in my project, this is my code:
#include <QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QDebug>
#include <QStringList>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase m_db = QSqlDatabase::addDatabase("QODBC");
m_db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=c:\\db.mdb;");
bool ok = m_db.open();
if(ok)
qDebug()<<"ok";
else
qDebug()<<"not ok";
return a.exec();
}
When I run it it shows mt ‘not ok’ I think I use wrong connection because QODBC driver in available,
another question is where ‘db.mdb’ file must be located? in debug folder or it must be attached to the project and how the connection string should change ?

Usually you don't need to install anything regarding drivers If you need to connect to an MS Access database with Qt. But if you don't have the necessary driver you should build it on your own.
You can connect to and MS Access database with something like this :
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=C:\\path\\to\\myDB.mdb");
if(db.open())
qDebug() << "oK";
else
qDebug() << db.lastError().text();

Related

How to create QT Login Page bedore Mainwindow?

My Qt windows application is ready, but when the application opens, I want the login dialog to be opened, how can I do this? I'm new to Qt and C++. It would be great if it was descriptive.
You have many ways to achieve that... QDialog is a nice way. Here is a short sample using QInputDialog.
One solution could be to add this code in your main.cpp file, and to load the mainwindow only if the credentials are ok.
#include "gmainwindow.h"
#include <QApplication>
#include <QInputDialog>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GMainWindow w;
QString login = QInputDialog::getText(NULL, "Login","Name ?",QLineEdit::Normal);
if (login == "USER")
{
w.show();
}
else
{
//display an error message
return a.quit();
}
return a.exec();
}
Of course you may want to put an encrypted password and other things, but the idea will be more or less the same.

How to list /dev/sda usb storages mounted with a combobox

I'm looking for the way to show up usb storage path when they are plugged in, the path must be shown in a combobox (in a gui that I'm designing with qt creator (qt 5.9)). I have been searching how to do it but I have not found anything. What I want it's something like:
https://catenarios2.files.wordpress.com/2012/11/002.jpg
Could you please help me to carry on my project? I would be very grateful if you provide an example.
Thank you a lot
The basic idea is the same -- you launch Linux tool via QProcess and parse the result. Here is a simple sketch:
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
#include <usb.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QProcess devList;
devList.start("lsblk", QStringList() << "-o" << "KNAME");
if (!devList.waitForStarted())
return false;
if (!devList.waitForFinished())
return false;
QString result = QString(devList.readAll());
qDebug() << result;
return a.exec();
}
You can use any other siutable command (quite easy to find them) and should improve parsing, of course, but generally it's all the same.
AFAIK, mount points could be obtained from /proc/mounts with something like...
#include <QCoreApplication>
#include <mntent.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
struct mntent *ent;
FILE *aFile;
aFile = setmntent("/proc/mounts", "r");
if (aFile == NULL) {
perror("setmntent");
exit(1);
}
while (NULL != (ent = getmntent(aFile))) {
printf("%s %s\n", ent->mnt_fsname, ent->mnt_dir);
}
endmntent(aFile);
return a.exec();
}
Better than cat launching or someting else, also taken from some snippet and should be improved.
And, finally, in case you'll need USD device info, it could be something like...
#include <QCoreApplication>
#include <usb.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
struct usb_bus *bus;
struct usb_device *dev;
usb_init();
usb_find_busses();
usb_find_devices();
for (bus = usb_busses; bus; bus = bus->next)
{
for (dev = bus->devices; dev; dev = dev->next)
{
printf("Trying device %s/%s\n", bus->dirname, dev->filename);
printf("\tID_VENDOR = 0x%04x\n", dev->descriptor.idVendor);
printf("\tID_PRODUCT = 0x%04x\n", dev->descriptor.idProduct);
}
}
return a.exec();
}
This needs sudo apt-get libusb-dev + compiling with -lusb.
Not really much of Qt in the problem and more fundamental "coding" solutions possible, but hopefully that'll give you a push towards appropriate solution.

How to set OffTheRecord profile for QWebEngineView?

How to setup OffTheRecord profile for QWebEngineView?
I use QT5.10 for Linux.
I am going to use it in embedded environment with read-only filesystem and I need to prevent WebEngine writing files and creating folders in filesystem.
#include <QApplication>
#include <QWebEngineView>
#include <QWebEngineSettings>
#include <QWebEngineProfile>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWebEngineView view;
auto profile = view.page()->profile();
profile->setHttpCacheType(QWebEngineProfile::MemoryHttpCache);
profile->setPersistentCookiesPolicy(QWebEngineProfile::NoPersistentCookies);
//profile->setPersistentStoragePath(nullptr);
std::cout << "StoragePath: " << profile->persistentStoragePath().toStdString() << std::endl;
std::cout << "isOffTheRecord: " << profile->isOffTheRecord() << std::endl;
profile->settings()->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true); // Since Qt5.7
profile->settings()->setAttribute(QWebEngineSettings::XSSAuditingEnabled, false);
view.setUrl(QUrl(QStringLiteral("http://localhost/index.html")));
view.resize(1920, 1080);
view.show();
return a.exec();
}
Try this configuration:
First of all, disable any possible cookie. Use setPersistentCookiesPolicy and set it to NoPersistentCookies
If you can write in to a given folder, try to save all temporal files in a secure storage:
auto *profile = QWebEngineProfile::defaultProfile();
profile->setCachePath("yourfolder");
profile->setPersistentStoragePath("yourfolder");
This should give you the control of all the temporal files that are generated by the Web Engine.
If not, taking a look in to Qt repo, you can see that the variable that manage this state is controlled in BrowserContextAdapter, this variable is set up to false, if the storage path is empty while creating the browser context.
So if you create your own QWebEngineProfile with an empty QString as path and use it as default profile:
QWebEngineProfile* profile = new QWebEngineProfile(QString(), parent)
std::cout << "isOffTheRecord: " << profile->isOffTheRecord() << std::endl; // Should return true
This can be done easily if you use it to create any single QWebEnginePage manually using this profile and set it in your QWebEngineView using setPage:
engineview->setPage(new QWebEnginePage(profile, parent));
The documentation for QWebEngineProfile's default constructor states:
Constructs a new off-the-record profile with the parent parent.
An off-the-record profile leaves no record on the local machine, and
has no persistent data or cache. Thus, the HTTP cache can only be in
memory and the cookies can only be non-persistent. Trying to change
these settings will have no effect.
Once you've created a default QWebEngineProfile, pass it to a QWebEnginePage and set that as the page in your QWebEngineView.
Here's a simple example that compiles and runs (tested on Mac OS):
#include <QApplication>
#include <QWebEngineView>
#include <QWebEngineSettings>
#include <QWebEnginePage>
#include <QWebEngineProfile>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWebEngineView view;
QWebEngineProfile profile;
QWebEnginePage page(&profile);
qDebug() << "StoragePath:" << profile.persistentStoragePath();
qDebug() << "isOffTheRecord:" << profile.isOffTheRecord();
view.setPage(&page);
view.setUrl(QUrl(QStringLiteral("http://www.stackoverflow.com/")));
view.show();
return a.exec();
}
When running the above you should see this appear in standard out:
StoragePath: ""
isOffTheRecord: true

How to create a directory using QT (QDir) in Linux?

I have been trying to create a directory in root directory of Linux. But as I am not much familiar with Linux platform I am unable to write the correct program in QT. Can you please have a look at my code and tell me where did I did mistake?
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QString>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QDir mDir;
QString mpath="/home/qtfile";
if (!mDir.exists(mpath))
{
mDir.mkpath(mpath);
qDebug() <<"Created";
}
else if (mDir.exists(mpath))
{
qDebug() <<"Already existed";
}
else
{
qDebug()<<"Directory could not be created";
}
return a.exec();
}
Thank you for your time and consideration
EDIT:- Thank you everyone. Now this problem is solved
This might be the issue of access rights #SamratLuitel is writing about in the comments.
Hence, you could try to give it a go in the proper home location, for example:
const QString& homePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
QDir dir(homePath);
if (dir.mkdir("somedir"))
{
//success
}

Connecting to the new Bluez HDP plugin using DBUS from QT/C++

I'm attempting to get readings from a device using the bluetooth Health Device Profile (specifically, an Nonin Onyx II 9560BT). Using this guide, I've been able to do so using python over dbus. Now I'm trying to port it over to C++, and as I'm already using QT in the application, I'm using the QT DBus bindings.
So far I've gotten to the following short program based on this API to test it:
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtDBus/QtDBus>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
if (!QDBusConnection::sessionBus().isConnected()) {
fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
"To start it, run:\n"
"\teval `dbus-launch --auto-syntax`\n");
return 1;
}
QDBusInterface iface("org.bluez","/org/bluez","org.bluez.HealthManager",QDBusConnection::systemBus(),0);
QVariantMap map;
map.insert("DataType",ushort(1004));//same result with simply 1004
map.insert("Role","Sink");
map.insert("Description","HDP Test Manager"); //Optional
//map.insert("ChannelType","Reliable");//Optional, same result with or without
//QList<QVariant> argumentList;
//argumentList.append(map);
QDBusPendingReply<> r = iface.call("CreateApplication",map);
qDebug() << r.reply();
qDebug() << r.error();
return 0;
}
As far as I can tell, the dict object taken by "CreateApplication" corresponds to an a{sv} which in QT corresponds to the QVariantMap.
However, I keep getting this error:
QDBusMessage(type=Error, service="", error name="org.bluez.Error.InvalidArguments", error message="Invalid arguments in method call", signature="", contents=([]) )
Question: What am I doing wrong?
Based on the guides at freedesktop.org, the qt docs and the mighty google, this is as far as I've gotten.
Thanks for any/all help!
/Keyz182
It works now. It seems that the ushort(0x1004) was getting cast by the QVariant to an int, and thus being picked up as a uint32 by the bluez code, which is not what was expected.
To fix it I did the following (there may be another way, but this worked for me).
I added a Metatype declaration for ushort, then registered it. then, created a QVariant containing the value, and used the QVariants convert method to set the metatype as a ushort (or uint16 when exposed to dbus).
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtDBus/QtDBus>
Q_DECLARE_METATYPE(ushort); //Added this to declare ushort as a metatype
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
int ushorttype = qDBusRegisterMetaType<ushort>(); //Register the ushort metatype and get it's id
if (!QDBusConnection::sessionBus().isConnected()) {
fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
"To start it, run:\n"
"\teval `dbus-launch --auto-syntax`\n");
return 1;
}
QDBusInterface iface("org.bluez","/org/bluez","org.bluez.HealthManager",QDBusConnection::systemBus(),0);
QVariant dt(0x1004);
dt.convert((QVariant::Type)ushorttype); //convert to the new type
QVariantMap map;
map.insert("DataType",dt);
map.insert("Role","Sink");
map.insert("Description","HDP Test Manager"); //Optional
QDBusPendingReply<> r = iface.call("CreateApplication",map);
qDebug() << r.isValid();
qDebug() << r.reply();
return 0;
}