Displaying database values with radio button selection in Qt? - qt

I want to show some database row values with radio button selection in Qt GUI. How this can be accomplished?. This could be done using foreach loop I guess. I have studied a bit about the following classes :
1) QMainWindow
2) QSqlTableModel
3) QTableWidget.
But which one satisfies my requirement? I am not able to implement it, please guide me. Thanks in advance.
I have implemented upto this in my source file-
main.cpp:
#include <QtGui/QApplication>
#include <QtSql>
#include <QTableWidget>
#include <QMessageBox>
#include "mainwindow.h"
#include <QRadioButton>
#include <QVBoxLayout>
#include <QGroupBox>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableWidget* table = new QTableWidget();
table->setWindowTitle("Connect to Mysql Database Example");
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("guests");
db.setUserName("sri");
db.setPassword("******");
if (!db.open())
{
QMessageBox::critical(0, QObject::tr("Database Error"),
db.lastError().text());
}
QSqlQuery query("SELECT * FROM new_members");
table->setColumnCount(query.record().count());
table->setRowCount(query.size());
int index=0;
while (query.next())
{
table->setItem(index,0,new QTableWidgetItem(query.value(0).toString()));
table->setItem(index,1,new QTableWidgetItem(query.value(1).toString()));
index++;
}
// This is sample radiobutton from QGroupBox class. Like this I need to implement the values from DB in with radio button selections for each value
QMainWindow *window = new QMainWindow();
window->setWindowTitle(QString::fromUtf8("QGroupBox"));
window->resize(400, 400);
QGroupBox *groupBox = new QGroupBox("Radio Buttons");
QRadioButton *radio1 = new QRadioButton("Radio button 1");
radio1->setChecked(true);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(radio1);
groupBox->setLayout(vbox);
window->setCentralWidget(groupBox);
window->show();
table->show();
//MainWindow w; w.show();
return a.exec();
}

Use a QSqlTableModel to drive a QTableView, you will need a custom QStyledItemDelegate to draw the QRadioButton (yes I said draw, and not create), and create an editor widget (of course that really will be a QRadioButton).
This is quite a big job, so you will need to read the above class' docs to reimplement the bits you need. Start with the MVC documents.

Related

How to implement reactive programming rx in Qt creator?

I'm new to QT please help me with how to implement reactive programming in Qt
If you want to use QML, then reactive programming will be very easy. Item properties in QML are naturally of reactive nature (just write a "java script" expression which uses other properties and the reactive connection will be established). Since Qt6, property bindings are available also in C++, see https://www.youtube.com/watch?v=pN0pRBUqrrc
Moreover, you can use property bindings by KDAB https://www.kdab.com/signals-slots-properties-bindings/
There is a project called rqxt that you may want to look into. Check out the samples folder.
For example, this is a sample for signals and slots:
#include <QApplication>
#include <QDebug>
#include <QKeyEvent>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>
#include <rxqt.hpp>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
auto widget = std::unique_ptr<QWidget>(new QWidget());
auto layout = new QVBoxLayout;
widget->setLayout(layout);
{
auto e0 = new QLineEdit("Edit here");
auto e1 = new QLineEdit;
e1->setEnabled(false);
layout->addWidget(e0);
layout->addWidget(e1);
rxqt::from_signal(e0, &QLineEdit::textChanged)
.map([](const QString& s) { return "[[[" + s + "]]]"; })
.subscribe([e1](const QString& s) { e1->setText(s); });
rxqt::from_event(e0, QEvent::KeyPress)
.subscribe([](const QEvent* e) {
auto ke = static_cast<const QKeyEvent*>(e);
qDebug() << ke->key();
});
}
widget->show();
return a.exec();
}

My Qt 5.5 QPushButton Button not showing up in window (Win7)

I'm doing the Udemy C++ Qt tutorial. The idea is to have a QPushButton button in a window.
When I run this, I get an empty window. Using Qt 5.5 in Win7.
Here are my files:
main.cpp
#include<QApplication>
#include"S_S.h"
int main(int argc, char *argv[])
{
QApplication app(argc,argv);
S_S MyTest;
MyTest.show();
return app.exec();
}
S_S.h
#ifndef S_S_H
#define S_S_H
#include<QApplication>
#include<QWidget>
#include<QPushButton>
class S_S : public QWidget
{
public:
S_S();
private:
QPushButton *Button1;
};
#endif // S_S_H
S_S.cpp
#include"s_s.h"
S_S::S_S():QWidget()
{
Button1=new QPushButton;
Button1->setText("Cancel");
connect(Button1,SIGNAL(clicked()),qApp,SLOT(quit()));
}
You probably want to construct the QPushButton and pass in a parent widget:
Button1 = new QPushButton(this);
I assume you want the S_S instance to be the parent.
You might also want to set the size and location of the button:
Button1->setGeometry(QRect(QPoint(100, 100), QSize(200, 50)));
There is an example here of using QPushButton.

Undesirable text overlapping

When I edit the QTableView the old text is not cleared and so the new text overlaps it. How can I avoid this behaviour?
The code:
#include <QApplication>
#include <QtSql>
#include <QtGui>
#include <QTableView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase db1 = QSqlDatabase::addDatabase("QSQLITE");
db1.setDatabaseName(":memory:");
db1.open();
QSqlQuery("CREATE TABLE test (a integer primary key, s text)");
QSqlQuery("INSERT INTO test VALUES (1, 'aaa');");
QSqlTableModel *model = new QSqlTableModel(0, db1);
model->setTable("test");
model->select();
QTableView *view = new QTableView;
view->setModel(model);
view->show();
return a.exec();
}
I have simular issue with dynamic QLabel.
When label text is updated new text was overlaped with old one. The problem was related to transparent background color.
As you find out the solution for you is to use such stylesheet QTableView::item {}
Complete Code:
view->setStyleSheet("QTableView::item {}");

How to use TAB Key to focus one of two qpushbutton

In a widget I put two QPushButton (let's say "OK" at left and "EXIT" at right).
They regularly work when I press them using the mouse.
Suppose I want to switch from one to the other using TAB key: is it possible?
And how can do this?
On some platforms, keyboard focus navigation among buttons is a default behavior, but on some it isn't.
If you wish keyboard navigation on all platforms, the buttons should have a Qt::StrongFocus policy set on them. Note that the shortcut used to trigger the buttons is also platform-specific. E.g. on OS X you'd use Space.
#include <QtWidgets>
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget w;
QVBoxLayout layout{&w};
// Individual Buttons
QPushButton p1{"button1"}, p2{"button2"};
for (auto p : {&p1, &p2}) {
layout.addWidget(p);
p->setFocusPolicy(Qt::StrongFocus);
}
// A button box
QDialogButtonBox box;
for (auto text : {"button3", "button4"})
box.addButton(text, QDialogButtonBox::NoRole)->setFocusPolicy(Qt::StrongFocus);
layout.addWidget(&box);
w.show();
return app.exec();
}
I tried it out on KDE/Ubuntu. It works automatically.
main.cpp
#include <QApplication>
#include "mainwindow.hpp"
int main(int argc, char** args) {
QApplication app(argc, args);
MainWindow m;
m.show();
return app.exec();
}
mainwindow.hpp
#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include <QMainWindow>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow();
};
#endif // MAINWINDOW_HPP
mainwindow.cpp
#include "mainwindow.hpp"
#include <QPushButton>
#include <QVBoxLayout>
MainWindow::MainWindow() : QMainWindow() {
auto* w = new QWidget;
auto* l = new QVBoxLayout;
auto* p1 = new QPushButton("ok");
auto* p2 = new QPushButton("exit");
l->addWidget(p1);
l->addWidget(p2);
w->setLayout(l);
setCentralWidget(w);
}
a.pro
TEMPLATE = app
TARGET = a
INCLUDEPATH += .
QT += widgets
HEADERS += mainwindow.hpp
SOURCES += main.cpp mainwindow.cpp
QMAKE_CXXFLAGS += -std=c++14
Edit: Apparently the buttons switch focus, but pressing enter does nothing. I guess you have to use focus-related mechanics (search for "focus" in the QWidget documentation) and implement it yourself. Or have a look at QDialog (as a replacement for QMainWindow in my example). It should have some meaningful default behavior for the enter and escape buttons.
Side note: Maybe you rather want to use the QDialogButtonBox for ok- and exit-buttons in your project. It's the cross-platform way of displaying OK/Cancel/Accept/Reject/... buttons because their arrangement differs between platforms. And this class can help you with that.
It is easier than all that code. Just use setFocusPolicy with Tabfocus on both buttons like this:
yourButtonOk->setFocusPolicy(Qt::TabFocus);
yourButtonExit->setFocusPolicy(Qt::TabFocus);

remove extra widget/window in Qt

probably a simple question: I just created a new project in Qt creator and I set it to use QWidget when I created it, now how do I get rid of the window that it automatically creates when I run it? I also created my own QWidget window which I want to be the only window.
#include "widget.h"
#include <QtGui>
Widget::Widget()
{
QWidget* window = new QWidget;
addBtn = new QPushButton("Add Module");
text = new QTextEdit();
text->setReadOnly(true);
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(addBtn,5);
layout->addWidget(text);
window->setLayout(layout);
window->show();
}
Widget::~Widget()
{
}
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
change it like this
Widget::Widget()
{
addBtn = new QPushButton("Add Module");
text = new QTextEdit();
text->setReadOnly(true);
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(addBtn,5);
layout->addWidget(text);
this->setLayout(layout);
}
and try to have some time on look and try some of Qt Example (you can find it in Qt Creator)
and there is about 100 short video to learn quickly basic stuff on Qt
Qt is fun, enjoy it.

Resources