I am totally new to Qt and just want to play around a little. I want to try to fill a ComboBox with values from a DB
I have got the following code:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setHostName("LOCALHOST");
db.setDatabaseName("rms32");
if(db.open())
{
QSqlQuery query;
query.prepare("select user_name from T_USER");
if(query.exec())
{
this->model = new QSqlQueryModel();
this->model->setQuery(query);
qDebug() << this->model->rowCount();
qDebug() << this->model->columnCount();
ui->_UsernameCB->setModel(this->model);
//ui->_UsernameCB->setModelColumn(0);
qDebug() << "Last error: " << db.lastError().text();
qDebug() << "Connection opened successfully";
}
db.close();
}
The rowCount and colCount gives me 1, corresponding to my DB, but the user_name is not displayed in the Combobox.
Can anyone point me to the error?
I cannot reproduce your problem. I have the very simply class below inheriting from QComboBox. I went for an sqlite database but otherwise most lines are pretty much exactly as in your case and it correctly displays the one entry in the DB.
If you replace the DB in the code with yours, do you get the entry correctly displayed?
combobox.h
#ifndef MYCOMBOBOX_H
#define MYCOMBOBOX_H
#include <QComboBox>
QT_FORWARD_DECLARE_CLASS(QSqlQueryModel);
class ComboBox : public QComboBox
{
public:
ComboBox(QWidget *widget = 0);
QSqlQueryModel *model;
};
#endif
combobox.cpp
#include "combobox.h"
#include <QSqlDatabase>
#include <QSqlQueryModel>
#include <QSqlQuery>
ComboBox::ComboBox(QWidget *parent) :
QComboBox(parent)
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("db.db");
if(db.open())
{
QSqlQuery query;
query.prepare("select * from TEST");
if(query.exec())
{
this->model = new QSqlQueryModel;
this->model->setQuery(query);
this->setModel(this->model);
}
db.close();
}
}
main.cpp
#include <QApplication>
#include <QDialog>
#include <QHBoxLayout>
#include "combobox.h"
int main(int argc, char** argv)
{
QApplication app(argc,argv);
QDialog dialog;
ComboBox box;
QHBoxLayout layout;
layout.addWidget(&box);
dialog.setLayout(&layout);
dialog.show();
return app.exec();
}
Related
I'm relatively new to boost-asio and I'm wondering if it's possible to make it work with KDB+ api here.
I tried something like the below but it doesn't seem to work properly,
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#define KXVER 3
#include "kx/k.h"
using boost::asio::ip::tcp;
namespace posix = boost::asio::posix;
class Feedhandler
{
public:
Feedhandler(boost::asio::io_service &io_service) : m_qsvc(io_service) {
char host[] = "localhost";
int port = 6812;
m_fd = khpu(host, port, "user:pass");
m_qsvc.assign(m_fd);
start_operations();
K ret = k(m_fd, ".u.sub", ks(""), ks(""), (K)0);
}
void start_operations()
{
boost::asio::async_read(m_qsvc, boost::asio::null_buffers(),
boost::bind(&Feedhandler::handle_read, this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_read(const boost::system::error_code& error, size_t size)
{
K data = k(m_fd,(S)0);
start_operations();
}
private:
int m_fd;
posix::stream_descriptor m_qsvc;
};
int main(int argc, char* argv[])
{
boost::asio::io_service io_service;
Feedhandler fh(io_service);
io_service.run();
return 0;
}
The handle_read method gets hit once and then subsequently there's no more call-backs.
Actually, it's better to use async_wait instead of async_read, like below,
m_qsvc.async_wait(boost::asio::posix::stream_descriptor::wait_read,
boost::bind(&Feedhandler::handle_read, this, boost::asio::placeholders::error) );
i'm new to vulkan.
when i call vkCreateInstance() , it crash , but i can't figure out what's the problem.
vkenumerateExtensionProperties return 0 extensoin count,and only VKLayer_LUNARG_api_dump found , it is weird .
core code are following , irrelevant code are removed.
Instance_Vulkan
#pragma once
#ifndef INSTANCE_VULKAN_HPP
#define INSTANCE_VULKAN_HPP
#include <vulkan/vulkan.h>
#include <vector>
#include <string>
#include <exception>
#include <iostream>
using namespace std;
namespace LB
{
class Instance_Vulkan
{
public:
bool isCreated = false;
VkInstance instance;
VkInstanceCreateInfo createInfo;
std::vector<const char*> extensions;
std::vector<const char*> layers;
Instance_Vulkan()
{
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.flags = 0;
createInfo.pNext = NULL;
createInfo.pApplicationInfo = NULL;
createInfo.enabledLayerCount = 0;
createInfo.ppEnabledLayerNames = NULL;
createInfo.enabledExtensionCount = 0;
createInfo.ppEnabledExtensionNames = NULL;
}
VkResult creat(const VkAllocationCallbacks* pAllocator=NULL)
{
if (isCreated)
return VK_SUCCESS;
else
{
VkResult result;
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
if(createInfo.enabledExtensionCount)
createInfo.ppEnabledExtensionNames = extensions.data();
createInfo.enabledLayerCount = static_cast<uint32_t>(layers.size());
if(createInfo.enabledLayerCount)
createInfo.ppEnabledLayerNames = layers.data();
if((result = vkCreateInstance(&createInfo, nullptr, &instance))!=VK_SUCCESS)
cout << "Error: fail to create Vulkan Instance ! " << endl;
if (result == VK_SUCCESS)
isCreated = true;
return result;
}
}
void destroy()
{
if (isCreated)
vkDestroyInstance(instance,nullptr);
isCreated = false;
}
};
}
#endif // !INSTANCE_VULKAN_HPP
following code invoke above class
#pragma once
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include<vulkan/vulkan.h>
#include <iostream>
#include <stdexcept>
#include <cstdlib>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include "Item.hpp"
#include"Window.hpp"
#include "Instance_Vulkan.hpp"
using namespace std;
namespace LB
{
class Application
{
public:
bool shouldClose = false;
virtual void mainLoop()
{
}
void init()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API,GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
initVulkan();
}
void initVulkan()
{
// set the application info
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Hellp Triangle";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName= "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
appInfo.pNext = NULL;
// set papplicatoinInfo
instance.createInfo.pApplicationInfo = &appInfo;
if (instance.creat()!= VK_SUCCESS)
throw std::runtime_error("Error: fail to create vulkan instance ");
}
void cleanUp()
{
glfwTerminate();
instance.destroy();
}
int run(int argc=0,char* argv[]=0)
{
init();
try {
for (;!shouldClose;)
mainLoop();
}
catch (const std::exception e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
cleanUp();
return EXIT_SUCCESS;
}
private:
Instance_Vulkan instance;
};
}
#endif
there are main function
#include "pch.h"
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include "Application.hpp"
#include <iostream>
#include <cstdlib>
using namespace LB;
using namespace std;
int main()
{
Application app;
return app.run();
}
when i run the code,it crash
'result image'
My Environment:
Win10 debug 64bit
vs2017
Gtx 940m driver: 416.94
i install lunarg sdk 1.1.85.0 , run the cube.exe and also compile the demo successfully
I have this piece of code that I developed just to address a problem that I have in another large program that I am developing.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <limits.h>
#include <string>
#include <iostream>
using namespace std;
void processLine (char []);
void readLine(char []);
const int LIMIT = 512;
int main(int argc, char *argv[])
{
char oneLine[LINE_MAX];
readLine(oneLine);
return 0;
}
void readLine(char line[])
{
processLine(line);
//Otherstuff
------------
}
void processLine(char line[])
{
pid_t process;
int child_status;
string input;
cout << "Input: ";
cin >> input;
process = fork();
if(process == 0)
{ // do nothing
}
else
{
//parent
if(input == "quit")
{
printf("Quit command found ! \nExiting ");
for(int i = 0;i < 3;i++)
{
printf(".");
fflush(stdout);
sleep(1);
}
printf("\n");
exit(0);
}
else
{
wait(&child_status);
}
}
}
My goal is simple, When the user enter quit.
I will just display
Quit command found
Exiting ...
And there is a delay of one second between each of these three dots.
However the output that I get is
Quit command found
Exiting . other stuff ..
However, what seems to happen is that the parent process returns and then executes other stuff from the calling function before it continues to print the other two dots. How would I avoid the parent process from doing that ?
Use waitpid() like this:
pid_t childPid;
childPid = fork();
...
int returnStatus;
waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate.
Use it here
if(childPid == 0) // fork succeeded
{
// Do something
exit(0);
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
waitpid(childPid, &returnStatus, 0);
}
I created a GUI to play two videos from two cameras, one camera is a USB camera, and another one is integrated in my laptop. My code is simple, I have three files:
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QCamera>
#include <QCameraInfo>
#include <QCameraImageCapture>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QList <QCameraInfo> camList;
QCamera *camera1;
QCamera *camera2;
private slots:
void onCameraChanged(int);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
camera1 = NULL;
camera2 = NULL;
connect(ui->cameraComboBox,static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),this,
&MainWindow::onCameraChanged);
camList = QCameraInfo::availableCameras();
for(QList <QCameraInfo>::iterator it = camList.begin();it!=camList.end();++it) {
ui->cameraComboBox->addItem(it->description());
}
}
MainWindow::~MainWindow() {
delete ui;
}
void MainWindow::onCameraChanged(int idx) {
if(camera1 != NULL) {
camera1->stop();
}
qDebug() << idx;
camera1 = new QCamera(camList.at(idx),this);
camera1->setViewfinder(ui->mainView);
camera1->setCaptureMode(QCamera::CaptureStillImage);
camera1->start();
if(camera2 != NULL) {
camera2->stop();
}
camera2 = new QCamera(camList.at(idx+1),this);
camera2->setViewfinder(ui->submainView);
camera2->setCaptureMode(QCamera::CaptureStillImage);
camera2->start();
}
I have deleted irrelevant code. Of course I have this in the *.pro file:
QT += multimedia multimediawidgets
My code compiles correctly, but it can only stream one video (camera1), and the other one shows nothing. The error I got is
CameraBin error: "Error starting streaming on device '/dev/video1'."
CameraBin error: "Could not negotiate format"
Any help will be appreciated.
I am reading a file from current directory
ifstream myfile;
myfile.open("version1.1.hex");
Now a situation is arising that if user updates version then there will be version1.2.hex or version1.3.hex ..so on in the current directory, but one file at a time will be present. I want to write a code now which will cater this future need of reading different file.
I'm writing this code in C++/CLI.
Since file listings are a bit environment-dependant I am not sure if this is helpful to you,
but here is an example how to achieve your goal under the mircosoft regime.
What is needed is the FindFirstFile / FindNextFile calls which query all files matching the fileSearchKey. Then you can use the cFileName part of WIN32_FIND_DATAA as parameter to your open command
string fileSearchKey = "version*";
WIN32_FIND_DATAA fd;
bool bFirstRun = true;
bool bFinishedRun = false;
HANDLE h = INVALID_HANDLE_VALUE;
while (!bFinishedRun)
{
if (bFirstRun)
{
h = FindFirstFileA(fileSearchKey.c_str(), &fd);
bFirstRun = false;
} else
{
if (FindNextFileA(h, &fd) != FALSE)
{
// Abort with error because it has more than one file or decide for the most recent version
} else
{
bFinishedRun = true;
}
}
}
// Load file
ifstream myfile;
myfile.open(fd.cFileName);
This code will look in the directory and take the first file, then quit.
WARNING : this will work only on linux
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <cstring>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
int main ()
{
char n[20];
unsigned char isFolder = 0x4;
unsigned char isFile = 0x8;
DIR *dir;
struct dirent *ent;
dir = opendir ("./");
if (dir != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
//folder sign
if(ent->d_type != isFolder && string(ent->d_name).find("version") != string::npos)
{
cout <<ent->d_name <<"\n";
// Your code
break;
}
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return 0;
}
cout << "=========" << endl;
}
In C++/CLI you should use the .net framework libraries for this. For instance you can use Directory::GetFiles.
using namespace System;
using namespace System::IO;
int main(array<System::String ^> ^args)
{
array<String^>^dirs = Directory::GetFiles(".", "version1.*.hex");
Collections::IEnumerator^ myEnum = dirs->GetEnumerator();
while (myEnum->MoveNext())
{
Console::WriteLine(myEnum->Current);
}
return 0;
}