How to make a QStandardItemModel from QStringList of file paths - c++

i'm new to C++ and Qt and can't seem to find the right solution for this. I want to create a QTreeView using a QStandardItemModel. I have a list of file/folder paths (within a QStringList) structured in a format like this:
Arena/Main/00078/a.txt
Arena/Main/00080/b.txt
Arena/Main/00080/collision/c.txt
Arena/Main/00080/light/d.txt
Arena/Main/00081/e.txt
Characters/f.txt
Characters/Main/g.txt
Characters/Main/someFolder/h.txt
I previously used a QFileSystemModel and made actual temporary directories, iterating through the list as a workaround:
QDir dir(temp_path);
if (!dir.exists(dir_string)){
dir.mkpath(dir_string);
}
QFile file(filepath_str);
file.open(QIODevice::WriteOnly);
Which gave me a working result like this: https://i.stack.imgur.com/ITzJz.png
However, the list can reach up to 10,000+ files making it a longer backwards workaround. I want to populate a QTreeView in a similar way using a QStandardItemModel created from the path list.

You can store the created paths in a map like this:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMap>
#include <QStandardItemModel>
class QStandardItem;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
void addPathRecusively(const QStringList &path_parts, QStandardItem *parent, int layer = 1);
QMap<QString, QStandardItem*> path_item_map_;
QStandardItemModel model_;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include <QStringList>
#include <QTreeView>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QStringList filenames =
{
"Arena/Main/00078/a1.txt",
"Arena/Main/00078/a2.txt",
"Arena/Main/00080/b.txt",
"Arena/Main/00080/collision/c.txt",
"Arena/Main/00080/light/d.txt",
"Arena/Main/00081/e1.txt",
"Arena/Main/00081/e2.txt",
"Arena/Main/00081/e3.txt",
"Characters/f.txt",
"Characters/Main/g.txt",
"Characters/Main/someFolder/h.txt",
};
for (auto &filename : filenames)
{
QStringList parts = filename.split("/");
parts.pop_back();
addPathRecusively(parts, model_.invisibleRootItem());
}
QTreeView *view = new QTreeView{this};
view->setModel(&model_);
this->setCentralWidget(view);
this->resize(500, 500);
}
MainWindow::~MainWindow()
{
}
void MainWindow::addPathRecusively(const QStringList &path_parts, QStandardItem *parent, int layer)
{
QStringList path_parts_to_layer;
std::copy(path_parts.begin(), path_parts.begin() + layer, std::back_inserter(path_parts_to_layer));
QString path = path_parts_to_layer.join("/");
auto item = path_item_map_.value(path);
if (item == nullptr)
{
item = new QStandardItem{path_parts_to_layer.last()};
path_item_map_.insert(path, item);
parent->appendRow({item, new QStandardItem});
}
if (path_parts.length() == layer)
{
auto file_count_index = model_.indexFromItem(item).siblingAtColumn(1);
model_.setData(file_count_index, file_count_index.data().toInt() + 1, Qt::DisplayRole);
}
else
addPathRecusively(path_parts, item, layer + 1);
}

Related

How do I get the text from a QTableView cell into a QlineEdit on click Qt5 C++

So I have been trying all day to find a working example of how to retrieve the data from a QtableView into a lineEdit as a QString. I think I have tried every example code online and have had zero success, I can not even figure out how to pull the row and column numbers from the tableView. Everything I have tried fails and I get the error that index is a unused parameter. This has got to be something simple that I am missing but I have not used QT or done any C++ programing since version 3 and am completely baffled. mainWindow.cpp is below. Thanks in advance for any help you can give me. BTW everything works fine except for the clicked slot.
#include <QDebug>
#include <QAbstractTableModel>
#include <QModelIndex>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->setupUi(this);
// Create a data model for the mapping table from a CSV file
csvModel = new QStandardItemModel(this);
csvModel->setColumnCount(2);
//csvModel->setHorizontalHeaderLabels(QStringList() << "Name" << "Number");
ui->tableView->setModel(csvModel);
// Open the file
QFile file("/home/foo.csv");
if ( !file.open(QFile::ReadOnly | QFile::Text) ) {
qDebug() << "File not exists";
} else {
// Create a thread to retrieve data from a file
QTextStream in(&file);
//Read to end
while (!in.atEnd())
{
QString line = in.readLine();
QList<QStandardItem *> standardItemsList;
for (QString item : line.split(",")) {
standardItemsList.append(new QStandardItem(item));
}
csvModel->insertRow(csvModel->rowCount(), standardItemsList);
}
file.close();
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
qDebug() << "test";
}
Header code below
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStandardItemModel>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_tableView_clicked(const QModelIndex &index);
private:
Ui::MainWindow *ui;
QStandardItemModel *csvModel;
};
#endif // MAINWINDOW_H
I think this is just a basic misunderstanding with regard to how signals/slots operate. Unless you're using the auto connect feature you need to manually connect a signal to a slot using one of the QObject::connect overloads. So in your constructor you need something like...
connect(ui->tableView, &QTableView::clicked, this, &MainWindow::[on_tableView_clicked);

Using QPainter to draw a line between QWidgets

I'm working on an application where I need to be able to draw a line between two QWidget objects. I have tried quite a few things, but my current attempt (which I think is in the right direction I just think I'm missing something) is to have the containing widget (which I called DrawWidget and which holds the QGridLayout that the QWidget objects are added to) override the paintEvent method and call the QPainter::drawLine() function.
The issues I'm having are that:
No matter how I try to get the position of the widgets, the endpoints of the line are always in the wrong place
Whenever I try to draw a second line, the first line that I drew gets erased.
Here is the paintEvent function of the containing widget:
void paintEvent(QPaintEvent *)
{
if (!drewSinceUpdate){
drewSinceUpdate = true;
QPainter painter(this);
painter.setPen(QPen(Qt::black));
painter.drawLine(start->geometry().center(), end->geometry().center());
}
}
I have tried many different ways to get the correct position of the widgets in the last line of paintEvent, which I will post some of the ways (I can't remember all of them):
painter.drawLine(start->pos(), end->pos());
painter.drawLine(start->mapToGlobal(start->geometry().center()), end->mapToGlobal(end->geometry().center()));
painter.drawLine(this->mapToGlobal(start->geometry().center()), this->mapToGlobal(end->geometry().center()));
painter.drawLine(start->mapTo(this, start->pos()), end->mapTo(this, end->pos()));
painter.drawLine(this->mapFrom(start, start->pos()), this->mapFrom(end, end->pos()));
And just to make my question clear, here is an example of what I am looking for, taken from QT Diagram Scene Example:
But this is what I end up getting:
Thank you for any help you can provide.
NOTE:
-start and end are both QWidget objects which I passed in using another method
-The hierarchy relevant to DrawWidget is:
QMainWindow
->QScrollArea
->DrawWidget
->QGridLayout
->Items <-- These are the things I want to connect
EDIT: To make a Complete and Verifiable example, here is the entirety of the relevant code.
MainWindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QPushButton>
#include <QScrollBar>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// Setting up the relevant hierarchy
ui->setupUi(this);
scrollArea = new QScrollArea();
setCentralWidget(scrollArea);
drawWidget = new DrawWidget();
gridLayout = new QGridLayout();
gridLayout->setSpacing(300);
drawWidget->setLayout(gridLayout);
scrollArea->setWidget(drawWidget);
scrollArea->setWidgetResizable(true);
AddItemSlot();
QApplication::connect(scrollArea->horizontalScrollBar(), SIGNAL(rangeChanged(int,int)), this, SLOT(scrollHorizontal()));
}
// This is just creating a single one of the example widgets which I want to connect
QWidget* MainWindow::CreateNewItem(){
QWidget* itemWidget = new QWidget();
itemWidget->setStyleSheet("background-color: lightgray");
QHBoxLayout* singleItemLayout = new QHBoxLayout();
itemWidget->setLayout(singleItemLayout);
QTextEdit* textEdit = new QTextEdit(std::to_string(counter++).c_str());
textEdit->setStyleSheet("background-color:white;");
singleItemLayout->addWidget(textEdit);
QVBoxLayout* rightSidePanel = new QVBoxLayout();
rightSidePanel->setAlignment(Qt::AlignTop);
QPushButton* button1 = new QPushButton("Top Button");
QApplication::connect(button1, SIGNAL(clicked(bool)), this, SLOT(AddItemSlot()));
rightSidePanel->addWidget(button1);
QWidget* rightPanelWidget = new QWidget();
rightSidePanel->setMargin(0);
rightPanelWidget->setLayout(rightSidePanel);
singleItemLayout->addWidget(rightPanelWidget);
itemWidget->setLayout(singleItemLayout);
itemWidget->setMinimumWidth(400);
itemWidget->setFixedSize(400,200);
return itemWidget;
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::scrollHorizontal()
{
scrollArea->ensureWidgetVisible(noteItems.back());
}
void MainWindow::AddItemSlot()
{
QWidget* w = CreateNewItem();
gridLayout->addWidget(w,currRow, currCol++);
if (!noteItems.empty()){
drawWidget->updateEndpoints(noteItems.back(), w);
}
noteItems.push_back(w);
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QGridLayout>
#include <QWidget>
#include <QMainWindow>
#include <QScrollArea>
#include <drawwidget.h>
#include "drawscrollarea.h"
#include <vector>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void scrollHorizontal();
void AddItemSlot();
private:
Ui::MainWindow *ui;
QWidget* CreateNewItem();
int counter = 0, currCol = 0, currRow = 0;
std::vector<QWidget*> noteItems;
QScrollArea* scrollArea;
DrawWidget* drawWidget;
QGridLayout* gridLayout;
};
#endif // MAINWINDOW_H
DrawWidget.cpp:
#include "drawwidget.h"
#include <QDebug>
#include <QRect>
DrawWidget::DrawWidget(QWidget *parent) : QWidget(parent)
{
}
void DrawWidget::paintEvent(QPaintEvent *)
{
if (!drewSinceUpdate){
drewSinceUpdate = true;
QPainter painter(this);
painter.setPen(QPen(Qt::black));
for (ConnectedPair pair : items){
const QWidget* from = pair.from;
const QWidget* to =pair.to;
QPoint start = from->mapToGlobal(from->rect().topRight() + QPoint(0, from->height()/2));
QPoint end = to->mapToGlobal(to->rect().topLeft() + QPoint(0, to->height()/2));
painter.drawLine(mapFromGlobal(start), mapFromGlobal(end));
}
}
}
void DrawWidget::updateEndpoints(QWidget* startIn, QWidget* endIn){
drewSinceUpdate = false;
items.push_back(ConnectedPair{startIn, endIn});
}
DrawWidget.h
#ifndef DRAWWIDGET_H
#define DRAWWIDGET_H
#include <QWidget>
#include <QPainter>
#include <QtCore>
#include <vector>
class DrawWidget : public QWidget
{
Q_OBJECT
public:
explicit DrawWidget(QWidget *parent = nullptr);
void updateEndpoints(QWidget* startIn, QWidget* endIn);
virtual void paintEvent(QPaintEvent *);
signals:
private:
struct ConnectedPair {
const QWidget* from;
const QWidget* to;
};
std::vector<ConnectedPair> items;
bool drewSinceUpdate = true;
};
#endif // DRAWWIDGET_H
For this case we use the function mapToGlobal() and mapfromGlobal(), since pos() returns a position with respect to the parent and this can cause problems if the widget has different parents.
drawwidget.h
#ifndef DRAWWIDGET_H
#define DRAWWIDGET_H
#include <QWidget>
class DrawWidget : public QWidget
{
Q_OBJECT
public:
explicit DrawWidget(QWidget *parent = nullptr);
void addWidgets(const QWidget *from, const QWidget *to);
protected:
void paintEvent(QPaintEvent *);
private:
struct WidgetsConnected {
const QWidget* from;
const QWidget* to;
};
QList<WidgetsConnected> list;
};
#endif // DRAWWIDGET_H
drawwidget.cpp
#include "drawwidget.h"
#include <QPainter>
DrawWidget::DrawWidget(QWidget *parent) : QWidget(parent)
{
}
void DrawWidget::addWidgets(const QWidget * from, const QWidget * to)
{
list.append(WidgetsConnected{from , to});
update();
}
void DrawWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
for(const WidgetsConnected el: list){
const QWidget* from = el.from;
const QWidget* to = el.to;
QPoint start = from->mapToGlobal(from->rect().topRight() + QPoint(0, from->height()/2));
QPoint end = to->mapToGlobal(to->rect().topLeft() + QPoint(0, to->height()/2));
painter.drawLine(mapFromGlobal(start), mapFromGlobal(end));
}
}
The complete example can be found here.

Storing Directory hierarchy in Datastructure Qt

How should i store data which is going into a TreeView? A Dictionary (QHash)? Plain Text? JSON?
My Hierarchy would be something like:
{
'Cloth': {
'Tissue':None,
'Leather': {
'Bandage': None
}
},
'Smoke': {
'White':{
'Smallscale': None,
'Largescale':None
}
}
}
Actions:
When I click a leaf-Element it will retrieve the Fullpath, like "Smoke/White/Smallscale" and this will be used as a key to place a SQL-Query.
I would use QStandardItem for every entry and when clicked, I would recursively call their parents, till I hit root.
Any thoughts?
Do you know QJsonTreeWidget?
Of course you don't need to use that library, but I do think you should use JSON in any case. It's almost a standard nowadays and very useful when we're working with trees.
Boost also has a wonderful library to work with JSON.
You can use one of the json library (like cajun) to parse json file.
This is the Qt part:
#include <QtGui>
#include <QTreeView>
class SimpleTreeView :public QTreeView
{
Q_OBJECT
public:
SimpleTreeView(QWidget *parent = 0);
public slots:
void slot_item_clicked(const QModelIndex &idx);
private:
QStandardItemModel *model;
};
#include <simpletreeview.h>
#include <qmessagebox.h>
#include <qobject.h>
SimpleTreeView::SimpleTreeView(QWidget *parent) : QTreeView(parent)
{
model = new QStandardItemModel(2,1);
QStandardItem *item1 = new QStandardItem("Cloth");
QStandardItem *item2 = new QStandardItem("Smoke");
model->setItem(0, 0, item1);
model->setItem(1, 0, item2);
QStandardItem *item3 = new QStandardItem("White");
item2->appendRow(item3);
QStandardItem *leaf = new QStandardItem("Smallscale");
leaf->setData("Smoke/White/Smallscale");
item3->appendRow(leaf);
setModel(model);
connect(this, SIGNAL(clicked(const QModelIndex &)), this, SLOT(slot_item_clicked(const QModelIndex &)));
}
void SimpleTreeView::slot_item_clicked(const QModelIndex & idx)
{
QString strData = model->itemFromIndex(idx)->data().toString();
QMessageBox::information(NULL, "Title", strData, QMessageBox::Yes, QMessageBox::Yes);
}
// main.cpp
#include <QApplication>
#include <simpletreeview.h>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
SimpleTreeView view;
view.show();
return app.exec();
}

Qt send data from form1 into form2 treeview component

I am pretty new to Qt, but I guess that I need to use signals and slots to send/receive data, at least in tutorials and other posts it's always like that.
This should be working:
Push Import button, select xls file -> right after we've selected it. We are running through the file and get the same sheet name and sheet table column headers for each sheet (then the user selects the column and all what that column contains; we are inserting into a database, etc)
I want to make a GUI application like this in my "excel-2-some-db" module:
I got two classes. First one - import_module:
import_module.h:
#ifndef IMPORTDB_MODULE_H
#define IMPORTDB_MODULE_H
#include <QtGui/QMainWindow>
#include <QAxObject>
#include <QAxWidget>
#include "ui_importdb_module.h"
#include "headers_selection.h"//select form
class importdb_module : public QMainWindow
{
Q_OBJECT
public:
importdb_module(QWidget *parent = 0, Qt::WFlags flags = 0);
~importdb_module();
//...
private:
Ui::importdb_moduleClass ui;
//...
headers_selection* select_form;
public slots:
void on_getExcelPath_clicked();
void on_pushButton1_clicked();
//signal we will send after read some sheets columns
signals:
void sendTreeViewData(QString &sheet_name, QStringList &sheet_headers);
};
#endif // IMPORTDB_MODULE_H
import_module.cpp
#include <QtGui>
#include <QApplication>
#include "importdb_module.h"
importdb_module::importdb_module(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
select_form = new headers_selection();
//to show form on click
connect(ui.pushButton1, SIGNAL(clicked()), select_form, SLOT(show()));
connect(this,
SIGNAL(sendTreeViewData(QString &sheet_name, QStringList &sheet_headers)),
select_form,
SLOT(recieveTreeViewData(QString &sheet_name, QStringList &sheet_headers)));
}
importdb_module::~importdb_module()
{
}
//....
//all file headers
void importdb_module::readSheetsHeaders(QAxObject* &_workbook, QAxObject* _worksheets, QAxObject* &_excel){
QAxObject* sheet_i;
int sheets_count = _worksheets->property("Count").toInt(); //get how much lists there, gonna choose one to import data
QString sheet_name;
QStringList sheet_headers;//sheet headers will store here
//sheets num starts from 1
for(int i=1; i<= sheets_count; i++){
sheet_i = _workbook->querySubObject("Worksheets(int)", i);//get teh list
sheet_name = sheet_i->property("Name").toString();//get teh name
//...
getTableHeaders(sheet_i, sheet_headers);
//says that we've send tree data into the form
emit sendTreeViewData(sheet_name, sheet_headers);
sheet_i->clear();
sheet_headers.clear();
}
delete sheet_i;
};
//...
headers_selection.h
#ifndef HEADERS_SELECTION_H
#define HEADERS_SELECTION_H
#include <QWidget>
#include "ui_headers_selection.h"
class headers_selection : public QWidget
{
Q_OBJECT
public:
headers_selection(QWidget *parent = 0);
~headers_selection();
private:
Ui::headers_selection ui;
public slots:
void recieveTreeViewData(QString &sheet_name, QStringList &sheet_headers);
};
#endif // HEADERS_SELECTION_H
headers_selection.cpp
#include "headers_selection.h"
headers_selection::headers_selection(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QStandardItemModel *model = new QStandardItemModel;
}
headers_selection::~headers_selection()
{
}
void headers_selection::recieveTreeViewData(QString &sheet_name, QStringList &sheet_headers)
{
//just test
QStandardItemModel *model = new QStandardItemModel;
model->setColumnCount(1);
model->setRowCount(5);
model->setData(model->index(0, 0), "some data0");
model->setData(model->index(1, 0), "some data1");
model->setData(model->index(2, 0), "some data2");
model->setData(model->index(3, 0), "some data3");
model->setData(model->index(4, 0), "some data4");
ui.treeView->setModel(model);
}
And after I import .xls and opening treeview selection windows - it's empty!
So I got two possible problems here
maybe sendTreeViewData does not invoke recieveTreeViewData or maybe I do something wrong with tree view inside recieveTreeViewData method.
Could somebody help me to fix it, please?
UPDATE
Well, I made a little changes (thanks to thomas_b, his answer shown me the way) in code and now it works!
//impordb_module.h
signals:
void sendTreeViewData(QString &sheet_name, QStringList &sheet_headers);
//heaqders_selection.h
public slots:
void recieveTreeViewData(QString &sheet_name, QStringList &sheet_headers);
//heaqders_selection.cpp
void headers_selection::recieveTreeViewData(QString &sheet_name, QStringList &sheet_headers)
{
qDebug()<<sheet_name<<" gotcha! ";
}
//in impordb_module.cpp
importdb_module::importdb_module(QWidget *parent, Qt::WFlags flags): QMainWindow(parent, flags){
connect(this, SIGNAL(sendTreeViewData(QString &,QStringList &)), select_form, SLOT(recieveTreeViewData(QString &,QStringList &)));
}
//...
void importdb_module::readSheetsHeaders(QAxObject* &_workbook, QAxObject* _worksheets, QAxObject* &_excel){
//...
getTableHeaders(sheet_i, sheet_headers);
//says that we've send tree data into the form
emit sendTreeViewData(sheet_name, sheet_headers);
//...
};
Maybe your connection failed because of the parameter names in your connect statement. Try change it to:
connect(this, SIGNAL(sendTreeViewData(QString,QStringList)),
select_form, SLOT(recieveTreeViewData(QString,QStringList)));

Store settings of qt application using QSettings

Hello I have created an application using qt and I managed to save some of its settings using QSettings.
void DoneIt::writeSettings()
{
QSettings settings("mycompany", "RightDoneIt");
settings.beginGroup("DoneIt");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.endGroup();
}
void DoneIt::readSettings()
{
QSettings settings("mycompany", "RightDoneIt");
settings.beginGroup("DoneIT");
resize(settings.value("size", QSize(400, 400)).toSize());
move(settings.value("pos", QPoint(200, 200)).toPoint());
settings.endGroup();
}
That works fine with the window position and size.
I have add some widgets in my application using the designer of qt and I would like to save their state too.
One of my widgets is a radio button and I call it radioButtonbnw
How can I save its state (checked or unchecked) ?
What are the best practises ?
Put them to QButtonGroup.
Use QButtonGroup::setId to set Id for each radio button in this group.
Save the Id of the checked button get by QButtonGroup::checkedId.
Get the pointer of this button using QButtonGroup::button(id) when restore, and call QAbstractButton::setChecked.
BTW: if you want to saves the current state of mainwindow's toolbars and dockwidgets, use QMainWindow::saveState.
Here an example widget with three QRadioButton
settingspane.h
#ifndef SETTINGSPANE_H
#define SETTINGSPANE_H
#include <QWidget>
#include <QSettings>
class SettingsPane
: public QWidget
{
Q_OBJECT
QSettings *settings;
public:
explicit SettingsPane(QWidget *parent = nullptr);
public slots:
void handle_rb_buttonReleased(int id);
};
#endif // SETTINGSPANE_H
settingspane.cpp
#include "settingspane.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QRadioButton>
#include <QButtonGroup>
SettingsPane::SettingsPane(QWidget *parent)
: QWidget(parent)
{
settings = new QSettings();
auto mlayout = new QVBoxLayout();
setLayout(mlayout);
// create some buttons
auto rb_frst = new QRadioButton("first");
auto rb_scnd = new QRadioButton("second");
auto rb_thrd = new QRadioButton("third");
// container to organize groups of buttons (no visual)
auto buttonGroup = new QButtonGroup();
buttonGroup->addButton(rb_frst,0);
buttonGroup->addButton(rb_scnd,1);
buttonGroup->addButton(rb_thrd,2);
// layout buttons for visual representation
auto rb_layout = new QHBoxLayout();
rb_layout->addWidget(rb_frst);
rb_layout->addWidget(rb_scnd);
rb_layout->addWidget(rb_thrd);
mlayout->addLayout(rb_layout);
// use Functor-Based Connection due to overloaded buttonReleased
connect( buttonGroup,
SIGNAL(buttonReleased(int)),
this,
SLOT(handle_rb_buttonReleased(int)));
// restore button from settings
int id = settings->value("buttonGroup").toInt();
buttonGroup->button(id)->setChecked(true);
}
void
SettingsPane::handle_rb_buttonReleased(int id)
{
// save new status to the settings
settings->setValue("buttonGroup", id);
}
Using this in a MainWindow
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow
: public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "settingspane.h"
#include <QTabWidget>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
auto cwidget = new QTabWidget();
setCentralWidget(cwidget);
auto settingsPane = new SettingsPane();
cwidget->addTab(settingsPane,"Settings");
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
results in: