QTreeWidget slow deletion after click - c++

I have made a QTreeWidget to display a very large and continuous data set. Since the data set is continuous, I delete initial rows when the total number of rows is greater than a specified amount.
The whole system is working correctly and displaying data.
But when I click on the tree view, the whole system slows done drastically. I have debugged. And the problem is in the deletion code, deleting each QTreeWidgetItem costs a lot of time after click ~ 20 ms
I debugged it in Qt source, and the problem seemed to be with QItemSelectionModel::setCurrentIndex
This line -> emit currentChanged(d->currentIndex, previous);
Now I couldn't debug it any further as I couldn't find out which slots are connected to this signal and slowing it down.
I am using Qt 4.7.1
I have pasted the whole code below:
Header file:
#ifndef WINDOW_H
#define WINDOW_H
#include <QWidget>
#include "ui_service.h"
#include <qtimer.h>
typedef std::pair<std::string, std::string> tSEntry;
typedef std::vector<tSEntry> tSFifo;
typedef struct tGUIData
{
std::string strCName;
std::string strFName;
std::string strPName;
std::string strMName;
std::string strMIDHex;
std::string strMIDDec;
std::string strTimeStamp;
std::string strRawDataHex;
std::string strRawDataDec;
tSFifo oSQueue;
} tGUIData;
class Window : public QWidget
{
Q_OBJECT
/// The Tree Widget where the data is shown
QTreeWidget* m_pTreeHead;
Ui::ListView* m_pForm;
int m_nMaxItemAmount;
QTimer m_oDataProducer;
QTimer m_oListClearer;
public:
Window();
~Window();
private slots:
void ProduceData();
void ClearTree();
void Window::AddEntry(tGUIData& tGUIData);
private:
void Window::DeleteItems();
};
#endif
Code file:
#include <QtGui>
#include "window.h"
#include <cstdlib>
#include <ctime>
Window::Window()
{
m_pForm = new Ui::ListView();
m_pForm->setupUi(this);
QHeaderView* pHeader = m_pForm->treeWidget->header();
pHeader->setResizeMode(0, QHeaderView::Interactive);
pHeader->setResizeMode(1, QHeaderView::Interactive);
pHeader->setResizeMode(2, QHeaderView::Interactive);
pHeader->setResizeMode(3, QHeaderView::Interactive);
pHeader->setResizeMode(4, QHeaderView::Stretch);
m_pTreeHead = m_pForm->treeWidget;
m_nMaxItemAmount = 1000;
m_oDataProducer.start(1);
m_oListClearer.start(10);
connect(&m_oDataProducer, SIGNAL(timeout()), this, SLOT(ProduceData()));
connect(&m_oListClearer, SIGNAL(timeout()), this, SLOT(ClearTree()));
}
std::string CreateRandomString(size_t nLength)
{
std::string o_str = "";
o_str.resize(nLength);
char cSymbols[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned int nIndexer = 0;
srand(static_cast<long int>(std::time(NULL)) + rand());
while (nIndexer < nLength)
{
o_str[nIndexer++] = cSymbols[rand() % 62];
}
return o_str;
}
void Window::ClearTree()
{
DeleteItems();
}
void Window::ProduceData()
{
for (size_t i = 0; i < 500; i++)
{
tGUIData oGUIData;
oGUIData.strCName = CreateRandomString(10);
oGUIData.strFName = CreateRandomString(10);
oGUIData.strMIDDec = CreateRandomString(10);
oGUIData.strMIDHex = CreateRandomString(10);
oGUIData.strMName = CreateRandomString(10);
tSEntry oSEntry;
oSEntry.first = CreateRandomString(10);
oSEntry.second = CreateRandomString(10);
oGUIData.oSQueue.push_back(oSEntry);
AddEntry(oGUIData);
}
}
Window::~Window()
{
m_oDataProducer.stop();
if (m_pForm)
{
delete m_pForm;
m_pForm = NULL;
}
}
void Window::DeleteItems()
{
while (m_pTreeHead->topLevelItemCount() >= m_nMaxItemAmount)
{
QTreeWidgetItem* pTreeWidget = m_pTreeHead->topLevelItem(0);
if (pTreeWidget)
{
delete pTreeWidget;
pTreeWidget = NULL;
}
}
}
void Window::AddEntry(tGUIData& oGUIData)
{
QTreeWidgetItem* pMessageItem = new QTreeWidgetItem(m_pTreeHead);
pMessageItem->setText(0, oGUIData.strCName.c_str());
pMessageItem->setText(1, oGUIData.strMName.c_str());
pMessageItem->setText(2, oGUIData.strTimeStamp.c_str());
pMessageItem->setText(3, oGUIData.strRawDataDec.c_str());
pMessageItem->setText(4, oGUIData.strPName.c_str());
while (!oGUIData.oSQueue.empty())
{
QTreeWidgetItem* pSubItem = new QTreeWidgetItem(pMessageItem);
tSEntry& sEntry = oGUIData.oSQueue.front();
pSubItem->setText(1, sEntry.first.c_str());
pSubItem->setText(2, sEntry.second.c_str());
oGUIData.oSQueue.erase(oGUIData.oSQueue.begin());
}
}

When you delete items disable update, like this:
QTreeWidget tw;
tw.setUpdatesEnabled(false);
To delete all items use(if items don't contains pointers):
tw.clear()
You don't need to delete items before QTreeWidget destructor.

Related

Style Sheet ignored on class inherited from QWidget [duplicate]

I have several custom widget in my current project. I wish to apply stylesheets to them and when I do so inside Qt Creator, it appears to work. However, when executing the program, no stylesheet is used. The stylesheets for the Qt widgets are working normally.
Does anyone have any advice?
WidgetUnits.h
#ifndef WIDGETUNITS_H
#define WIDGETUNITS_H
#include <QList>
#include <QWidget>
#include <QPainter>
#include <Widgets/JECButton.h>
#include <Unit.h>
#include <Time.h>
namespace Ui
{
class WidgetUnits;
}
class WidgetUnits : public QWidget
{
Q_OBJECT
public:
explicit WidgetUnits(QWidget *parent = 0);
~WidgetUnits();
void setNumTimes(const int& numTimes);
public slots:
void updatePictures(const Time* time);
protected:
void paintEvent(QPaintEvent *event);
private:
void checkNewQueue(const QList<QList<Unit*>*>* units);
Ui::WidgetUnits *ui;
const int pictureWidth; // The width of the Unit pictures.
const int pictureHeight; // The height of the Unit pictures.
QList<QList<JECButton*>*> buttonPictures; // The Units' pictures. The outer QList stores the QList of pictures for a given tick.
// The inner QList stores the JECButtons for the specific tick.
};
WidgetUnits.cpp
#include "WidgetUnits.h"
#include "ui_WidgetUnits.h"
WidgetUnits::WidgetUnits(QWidget *parent):
QWidget(parent),
ui(new Ui::WidgetUnits),
pictureWidth(36),
pictureHeight(36)
{
ui->setupUi(this);
}
WidgetUnits::~WidgetUnits()
{
delete ui;
}
void WidgetUnits::updatePictures(const Time *time)
{
// Only showing units that started to get built this turn.
checkNewQueue(time->getUnits());
checkNewQueue(time->getBuildings());
checkNewQueue(time->getUpgrades());
// Updating the position of the remaining pictures (after some were removed).
// Checking the maximum number of Units made in one tick.
int maxNewQueue = 0;
for (int a = 0; a < buttonPictures.length(); ++a)
{
if (buttonPictures.at(a)->length() > maxNewQueue)
{
maxNewQueue = buttonPictures.at(a)->length();
}
}
if (buttonPictures.length() > 0)
{
this->setGeometry(0, 0, buttonPictures.length() * 130,
maxNewQueue * (pictureWidth + 10) + 20);
QList<JECButton*>* tickButtons = 0;
for (int a = 0; a < buttonPictures.length(); ++a)
{
tickButtons = buttonPictures.at(a);
for (int b = 0; b < tickButtons->length(); ++b)
{
tickButtons->at(b)->move(a * 130, b * (pictureHeight + 10));
}
}
}
update();
}
void WidgetUnits::checkNewQueue(const QList<QList<Unit *> *> *units)
{
if (units != 0)
{
const Unit* currentUnit = 0;
JECButton* currentButton = 0;
for (int a = 0; a < units->length(); ++a)
{
buttonPictures.append(new QList<JECButton*>());
for (int b = 0; b < units->at(a)->length(); ++b)
{
currentUnit = units->at(a)->at(b);
// Verifying that there is an item in the queue and the queue action was started this turn.
if (currentUnit->getQueue() != 0 && currentUnit->getAction()->getTimeStart() == currentUnit->getAction()->getTimeCurrent()
&& (currentUnit->getAction()->getType() == Action::BUILD || currentUnit->getAction()->getType() == Action::TRAIN ||
currentUnit->getAction()->getType() == Action::UPGRADE))
{
buttonPictures.last()->append(new JECButton(this));
currentButton = buttonPictures.last()->last();
QImage* image = new QImage(currentUnit->getQueue()->getUnitBase()->getImage().scaled(pictureWidth, pictureHeight));
currentButton->setImage(*image);
currentButton->setGeometry(0, 0, currentButton->getImage().width(),
currentButton->getImage().height());
currentButton->setColorHover(QColor(0, 0, 225));
currentButton->setColorPressed(QColor(120, 120, 120));
currentButton->setImageOwner(true);
currentButton->setVisible(true);
}
}
}
}
}
void WidgetUnits::setNumTimes(const int &numTimes)
{
// Appending new button lists for added ticks.
for (int a = buttonPictures.length(); a < numTimes; ++a)
{
buttonPictures.append(new QList<JECButton*>());
}
}
void WidgetUnits::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
}
The widget is visible- I set a tooltip which it showed me (It's just the same color of the QScrollArea it's sitting in).
I had a similar problem and it was solved using jecjackal's comment. As sjwarner said, it would be much more noticeable in the form of an answer. So I'll provide it. For the benefit of any future viewers. Again, it isn't my answer! Appreciate jecjackal for it!
As it is said in the Qt's stylesheets reference, applying CSS styles to custom widgets inherited from QWidget requires reimplementing paintEvent() in that way:
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
Without doing it your custom widgets will support only the background, background-clip and background-origin properties.
You can read about it here: Qt Stylesheets reference in the section "List of Stylable Widgets" -> QWidget.
There is an answer much easier than writing your own paintEvent: subclass QFrame instead of QWidget and it will work right away:
class WidgetUnits : public QFrame
{
Q_OBJECT
....
For completeness, the same problem is present in PyQt. You can apply a stylesheet to a subclassed QWidget by adding similar code:
def paintEvent(self, pe):
opt = QtGui.QStyleOption()
opt.init(self)
p = QtGui.QPainter(self)
s = self.style()
s.drawPrimitive(QtGui.QStyle.PE_Widget, opt, p, self)
I had same problem with pyside. I post my solution just for completeness.
It is almost like in PyQt as Pieter-Jan Busschaert proposed.
only difference is you need to call initFrom instead of init
def paintEvent(self, evt):
super(FreeDockWidget,self).paintEvent(evt)
opt = QtGui.QStyleOption()
opt.initFrom(self)
p = QtGui.QPainter(self)
s = self.style()
s.drawPrimitive(QtGui.QStyle.PE_Widget, opt, p, self)
One other thing you need to make sure is that you define your custom widget in your css file the following way:
FreeDockWidget{...}
and not like often recommended
QDockWidget#FreeDockWidget{...}
Calling setAttribute(Qt::WA_StyledBackground, true) for the custom widget worked for me.
Setting Qt::WA_StyledBackground to true only works if you remember to add Q_OBJECT to your class. With these two changes you don't need to reimplement paintEvent.

Adding a Gtk::ListStore to Gtk::TreeView and adding rows to ListStore (gtkmm)

I want to be able to add a Gtk::ListStore to a Gtk::TreeView, the treeview was implemented through glade but I have created the ListStore in C++ and added columns and rows to it.
When I run the code it shows the window and the tree_view that has been loaded from the glade file but it is empty.
mainWindow.h:
#pragma once
#include <gtkmm.h>
class MainWindow {
protected:
Gtk::Window *main_window;
Gtk::TreeView *tree_view;
Glib::RefPtr<Gtk::ListStore> list_store;
public:
void init();
class ModelColumns : public Gtk::TreeModel::ColumnRecord
{
public:
ModelColumns() { add(name); add(age); }
Gtk::TreeModelColumn<Glib::ustring> name;
Gtk::TreeModelColumn<Glib::ustring> age;
};
};
mainWindow.cpp:
#include "mainWindow.h"
void MainWindow::init() {
auto app = Gtk::Application::create("org.gtkmm.example");
auto builder = Gtk::Builder::create_from_file("test.glade");
builder->get_widget("main_window", main_window);
builder->get_widget("tree_view", tree_view);
ModelColumns columns;
list_store = Gtk::ListStore::create(columns);
tree_view->set_model(list_store);
Gtk::TreeModel::Row row = *(list_store->append());
row[columns.name] = "John";
row[columns.age] = "30";
row = *(list_store->append());
row[columns.name] = "Lisa";
row[columns.age] = "27";
app->run(*main_window);
}
main.cpp:
#include "mainWindow.h"
int main() {
MainWindow m;
m.init();
}
tree_view->set_model(list_store);
tells tree_view to use list_store as its TreeModel, but it does not say what column from the list_store to render. In fact, the default behavior is that no column would be rendered.
To render both columns, you need to ask tree_view to append them.
// "Name" is column title, columns.name is data in the list_store
tree_view->append_column("Name", columns.name);
tree_view->append_column("Age", columns.age);
Gtkmm has an official tutorial book. This is the section on treeview. https://developer.gnome.org/gtkmm-tutorial/stable/sec-treeview.html.en

Custom Child Components Added But Not Visible

I am using the JUCE framework to create an audio plugin. I have created a Knob class which inherits from the Component class. My Knob class contains references to a Slider & a Label.
In my AudioProcessorEditor class, I initialize several Knob objects. However, none of the Components are visible at run-time. Am I doing something wrong or missing a step?
I have tried declaring Slider & Label objects directly inside of my AudioProcessorEditor class. When I do that, I am able to see the Slider & Label objects successfully at run-time. So I get the feeling that the issue involves my Knob class.
Knob.h
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
class Knob : public Component
{
public:
Knob(String, AudioProcessorEditor*);
~Knob();
void paint (Graphics&) override;
void resized() override;
String Name;
Label *KnobLabel;
Slider *KnobSlider;
AudioProcessorEditor *APE;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Knob)
};
Knob.cpp
#include "Knob.h"
Knob::Knob(String name, AudioProcessorEditor *ape)
{
// In your constructor, you should add any child components, and
// initialise any special settings that your component needs.
this->Name = name;
APE = ape;
KnobLabel = new Label(name);
KnobLabel->setColour(0x1000281, Colours::antiquewhite);
KnobLabel->setAlwaysOnTop(true);
KnobLabel->setFont(10);
KnobSlider = new Slider();
KnobSlider->setAlwaysOnTop(true);
addAndMakeVisible(KnobLabel);
addAndMakeVisible(KnobSlider);
}
void Knob::paint (Graphics& g)
{
/* This demo code just fills the component's background and
draws some placeholder text to get you started.
You should replace everything in this method with your own
drawing code..
*/
g.setColour(Colours::white);
g.fillAll();
}
void Knob::resized()
{
// This method is where you should set the bounds of any child
// components that your component contains..
auto bounds = getLocalBounds();
KnobSlider->setBounds(bounds.removeFromTop(getHeight()*8));
KnobLabel->setBounds(bounds);
}
PluginEditor.h
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "PluginProcessor.h"
#include "Knob.h"
#include "Model.h"
class MoonlightAudioProcessorEditor : public AudioProcessorEditor
{
public:
MoonlightAudioProcessorEditor (MoonlightAudioProcessor&);
~MoonlightAudioProcessorEditor();
void paint (Graphics&) override;
void resized() override;
Knob *OrbitKnob;
Knob *SpaceKnob;
Knob *InertiaKnob;
void ConfigureUI();
private:
OwnedArray<Knob> Knobs;
ComponentBoundsConstrainer ResizeBounds;
ResizableCornerComponent *Resizer;
MoonlightAudioProcessor& processor;
};
PluginEditor.cpp
#include "PluginProcessor.h"
#include "PluginEditor.h"
MoonlightAudioProcessorEditor::MoonlightAudioProcessorEditor (MoonlightAudioProcessor& p)
: AudioProcessorEditor (&p), processor (p)
{
setSize (400, 300);
ConfigureUI();
}
void MoonlightAudioProcessorEditor::ConfigureUI()
{
OrbitKnob = new Knob("Orbit", this);
SpaceKnob = new Knob("Space", this);
InertiaKnob = new Knob("Inertia", this);
Knobs.add(OrbitKnob);
Knobs.add(SpaceKnob);
Knobs.add(InertiaKnob);
for (Knob *knob : Knobs)
{
knob->KnobSlider->addListener(this);
addAndMakeVisible(knob);
knob->setAlwaysOnTop(true);
}
ResizeBounds.setSizeLimits(DEFAULT_WIDTH,
DEFAULT_HEIGHT,
MAX_WIDTH,
MAX_HEIGHT);
Resizer = new ResizableCornerComponent(this, &ResizeBounds);
addAndMakeVisible(Resizer);
setSize(processor._UIWidth, processor._UIHeight);
}
void MoonlightAudioProcessorEditor::paint (Graphics& g)
{
g.setColour (Colours::black);
g.fillAll();
}
void MoonlightAudioProcessorEditor::resized()
{
int width = getWidth();
int height = getHeight();
auto bounds = getLocalBounds();
auto graphicBounds = bounds.removeFromTop(height*.8);
auto orbitBounds = bounds.removeFromLeft(width/3);
auto spaceBounds = bounds.removeFromLeft(width/3);
if (OrbitKnob != nullptr)
{
OrbitKnob->setBounds(orbitBounds);
}
if (SpaceKnob != nullptr)
{
SpaceKnob->setBounds(spaceBounds);
}
if (InertiaKnob != nullptr)
{
InertiaKnob->setBounds(bounds);
}
if (Resizer != nullptr)
{
Resizer->setBounds(width - 16, height - 16, 16, 16);
}
processor._UIWidth = width;
processor._UIHeight = height;
}
Also, I have been using the AudioPluginHost application provided with JUCE to test my plugin. A lot of times the application will crash from a segmentation fault. Then I rebuild the plugin without changing anything and it will work.
I ended up figuring it out.
My components were being initialized after I set the size. A lot of the display logic was in the resize() function so I needed to set the size after component initialization.
You left out a call to Component::Paint(g) in Knob::Paint(Graphics& g)

C++/Qt Threads error without using threads

I am using a special form of the qt framework and it will look a bit complicated. But do not worry. It is the same as the original framework of qt. (And no I can't change it)
My intention of this program is to load a table in a tableview from the ui. The tableview should have as many rows and text as files that are in a directory. I take all files in the directory and put an filter on them. Only the selected one are counted and used afterwards.
And now to my problem:
I want to display the table like an Excel table: it should highlight the cell where my cursor (in my example it is an counter which goes up and down) stands right now (Currently I do not have a cursor, so I have to use a self-created "cursor". You will see it in the program what I mean).
I use a QStandardItemModel to display it and a QStandardItem to define it.
Because I want to change the color of the cells I use an QStandardItem array to save the cells one by one.
form.h:
#ifndef FORM_H
#define FORM_H
#include <QWidget>
#include <QTextTable>
#include <QFont>
#include <QFile>
#include <QDir>
#include <QTextStream>
#include <QString>
#include <QStringList>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QBrush>
namespace Ui {
class Form;
}
class Form : public QWidget
{
Q_OBJECT
public:
explicit Form(QWidget *parent = 0);
~Form();
void my_setCFGFromDirectory();
void my_Highlighted(int, bool);
void my_loadCFG(int);
private:
Ui::Form *ui;
QFile file;
QTextStream textstream;
QDir directory;
QString filename;
QStringList stringlist;
QStringList filter;
QStandardItemModel *model;
QStandardItem *tableitem;
QStandardItem* pointerTableitem[];
int max_files;
int w_counter;
bool check1;
bool check2;
bool check3;
};
#endif // FORM_H
and the
form.cpp
#include "form.h"
#include "ui_form.h"
#include "rbobject.h"
Form::Form(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
}
Form::~Form()
{
delete ui;
}
void Form::my_Highlighted(int actual_count, bool modus){
if(modus == 1){
w_counter = 0;
while(w_counter < max_files){
if(w_counter == actual_count){
pointerTableitem[w_counter]->setBackground(QBrush(QColor(130,180,255)));
}
w_counter++;
}
}
else
{
w_counter = 0;
while(w_counter < max_files){
pointerTableitem[w_counter]->setBackground(QBrush(QColor(255,255,255)));
w_counter++;
}
}
}
void Form::my_setCFGFromDirectory(){
directory.setPath("/etc/rosenbauer/CFG-Files");
filter << "*_CFG.ini";
stringlist = directory.entryList(filter); //takes the selected files and wriths them in a filelist
max_files = stringlist.count(); //Counts the selected files
pointerTableitem [max_files];
memset(pointerTableitem, 0, max_files*sizeof(int)); //The compiler can not see how many elements should be in the array at the time he constructs the array.
//So you have to use this to tell the compiler, how many elements it should create
model = new QStandardItemModel(max_files, 1, this); //Rows , Columns , this
model->setHorizontalHeaderItem(0, new QStandardItem(QString("CFG-Files"))); //Column , QStandarditem...name
for(w_counter = 0; w_counter != max_files; w_counter++){
tableitem = new QStandardItem();
tableitem->setBackground(QBrush(QColor(255,255,255)));
tableitem->setText(QString(stringlist[w_counter])); //Wriths text in the cell
qDebug() << tableitem->text();
pointerTableitem[w_counter] = tableitem; //Stacks the tableitems in a filelist
model->setItem(w_counter, 0, tableitem); //Row, Column , tableitem...text
}
w_counter = 0;
//pointerTableitem[2]->setBackground(QBrush(QColor(130,180,255))); //Test
ui->TableConfig->setModel(model); //Sets the table into the UI
}
void Form::my_loadCFG(int file_position){
check1 = 0;
check2 = 0;
directory.setPath("/etc/rosenbauer/etc/rosenbauer");
check1 = directory.remove("SA008_890560-001_CFG.ini");
check2 = directory.remove("reparsed/SA008_890560-001_CFG.ini_reparsed");
if(check1 && check2){
filename = pointerTableitem[file_position]->text();
check3 = QFile::copy("/etc/rosenbauer/CFG-Files/"+filename, "/etc/rosenbauer/SA008_890560-001_CFG.ini");
if(!check3){
qDebug() << "Error! Could not copy new CFG-file into directory";
}
}
else
{
qDebug() << "Error! Could not delete running CFG-file(s) from directory";
}
}
The main header rbobject45000.h
#ifndef RbObject45000_H
#define RbObject45000_H
#include "rbobject.h"
#include "form.h"
class RbObject45000 : public RbObject{
public:
RbObject45000();
RbObject45000(qint32 rbObjectId, RDataObject *dataobject, qint32 style, QObject *parent = 0);
RbObject45000(qint32 rbObjectId, qint32 style, qint32 prio, QObject *parent);
bool entered_ui;
bool entered_key;
short counter;
short w_count;
short delay_count;
short max_files;
short begin;
short end;
Form *f;
void exec();
~RbObject45000();
};
#endif // RbObject45000_H
And this is the main:
rbobject45000.cpp
RbObject45000::RbObject45000(qint32 rbObjectId, qint32 style, qint32 prio, QObject *parent):
RbObject(rbObjectId, style, prio, parent){
entered_ui = 0;
entered_key = 0;
counter = 0;
w_count = 1; //... whilecounter
delay_count = 0; //... delay for the deadtime
max_files = 0;
begin = 0;
end = 0;
f= new Form(); //f...name of the displayed UI
}
void RbObject45000::exec(){
//Opens the file on the display
if(getKey(RB_KEY_9) && getKey(RB_KEY_7) && entered_ui ==0){
f->show();
entered_ui = 1;
// Geting the Files from Directory
f->my_setCFGFromDirectory();
}
// Prescind them file in the table
if(entered_ui == 1 && delay_count == 2){
if(getKey(RB_KEY_7)){
counter--;
entered_key = 1;
if(counter < 0){
counter = 0;
}
}
else if(getKey(RB_KEY_9)){
counter++;
entered_key = 1;
if(counter > max_files){
counter = max_files;
}
}
if(entered_key == 1){
while(w_count <= max_files){
f->my_Highlighted(w_count, 0); //Cell , not highlighted
w_count++;
}
w_count = 0;
f->my_Highlighted(counter,1); //Cell , highlighted
entered_key = 0;
}
delay_count = 0;
}
else if(delay_count == 2){ //if delay == 2 and nobody hit a button
delay_count = 0;
}
delay_count++;
//Load the coosen file as programm-config in
if(entered_ui == 1){
if(getKey(RB_KEY_8)){
f->my_loadCFG(counter);
}
}
}
(RB_KEY_7-9 are buttons of a hardware-module, only have to click them)
So if I do it like this, the program will compile and start. If I press the buttons and the program run into the my_setCFGFromDirectory() it exits the window and stop running, but if the QStandardItem pointerTableitem is declared in the my_setCFGFromDirectory() everything works fine (but the pointerTableitem needs to be private).
The errors I get are:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is Form(0x167498), parent's thread is QThread(0x1414e8), current thread is QThread(0x15d2d8)
Segmentation fault
It appears to say I use a thread (I'm sure I don't). But I know it has something to do with pointerTableitem and the declaration in the header and cpp.
If I'm not mistaken the problem lies here:
model = new QStandardItemModel(max_files, 1, this);
You try to create a QStandardItemModel passing your Form instance this as a parent, the form was created on the main thread, this call apparently happens on another thread (the edits you made were not enough, it is still unclear if RbObject inherits QThread but you could check that yourself) and thus the error message.
Why not call the function on the main thread? Instead of doing this
f->show();
entered_ui = 1;
// Geting the Files from Directory
f->my_setCFGFromDirectory();
in a different thread, make a slot/signal pair for the Form class, put this code in the slot and fire the connected signal from RbObject45000::exec(). It is not correct to do UI manipulation from a non-UI trhead.

Memory leak with post requests and QNetworkAccessManager

I'm making a program that uses lots of timer and, at intervals of 4 seconds, does an online post to a php script.
I'm coding in QtCreator 5.1. I use classes just like the ones below.
The one below just populates a task list, but throughout the course of 8 to 12 hours, the memory that the program takes up just keep rising and rising gradually.
What am I doing wrong while using this class?
I have to be able to keep posting online like I already am, about every 4 to 8 seconds.
Here's a simple class for taking care of one of my processes:
Header file: tasklistprocess.h
#ifndef TASKLISTPROCESS_H
#define TASKLISTPROCESS_H
#include <QThread>
#include <QtCore>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QListWidget>
#include <QTabWidget>
#include "globalhelper.h"
#include "securityinfo.h"
class TaskListProcess : public QThread
{
Q_OBJECT
public:
explicit TaskListProcess(QListWidget *obj_main, QTabWidget *tabs_main, QString user, QObject *parent = 0);
signals:
void upTaskStorage(int key,QHash<QString,QString> item);
private:
GlobalHelper gh;
Securityinfo sci;
QNetworkAccessManager *nam;
QNetworkRequest request;
QByteArray data;
// this is the disposable params for reusage through out the class
QUrlQuery params;
QString post_data;
QString user_name;
QTimer *tasklist_tmr;
bool get_task_list;
QListWidget *obj;
QTabWidget *tabs;
private slots:
void setTaskList();
void replyFinished(QNetworkReply *reply);
void sendPost(QString file_name, QUrlQuery params);
};
#endif // TASKLISTPROCESS_H`
Source file: tasklistprocess.cpp
#include "tasklistprocess.h"
TaskListProcess::TaskListProcess(QListWidget *obj_main, QTabWidget *tabs_main, QString user, QObject *parent) :
QThread(parent)
{
user_name = user;
get_task_list = false;
obj = obj_main;
tabs = tabs_main;
tasklist_tmr = new QTimer(this);
connect(this,SIGNAL(started()),this,SLOT(setTaskList()));
connect(tasklist_tmr,SIGNAL(timeout()),this,SLOT(setTaskList()));
nam = new QNetworkAccessManager(this);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
request.setRawHeader( "User-Agent" , "Mozilla Firefox" );
// here we connect up the data stream and data reply signals
connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
void TaskListProcess::setTaskList()
{
qDebug() << "Your task list was set";
bool in = false;
if(!(tasklist_tmr->isActive()))
{
tasklist_tmr->start(10000);
in = true;
}
if(!(get_task_list))
{
params.clear();
params.addQueryItem("user_name", user_name);
params.addQueryItem("logged_in", "1");
sendPost("getTaskList.php",params);
get_task_list = true;
}
else
{
if(post_data.contains("|*|"))
{
//here i retrieve a piece of information from a php script which is stored in a custom string format
// here we clear the list for the new data to be put in
if(obj->count()>0)
{
obj->clear();
}
int key = 0;
foreach(QString inner_task,post_data.split("|*|"))
{
QHash<QString,QString> task_cont;
//qDebug() << " ";
if(inner_task.contains("*,*"))
{
foreach(QString task_val,inner_task.split("*,*"))
{
if(task_val.contains("*=*"))
{
QStringList key_pairs = task_val.split("*=*");
task_cont.insert(key_pairs[0],key_pairs[1]);
if(key_pairs[0] == "tt")
{
QString val_in;
if(key_pairs[1].length()>10)
{
// this sets the title to the shortened version
// if the string length is too long
val_in = key_pairs[1].left(10) + "....";
}
else
{
val_in = key_pairs[1];
}
obj->addItem("Task :" + QString::fromUtf8(key_pairs[1].toStdString().c_str()));
}
}
}
}
//task_storage.insert(key,task_cont);
emit upTaskStorage(key,task_cont);
key ++;
}
}
get_task_list = false;
}
// here we're checking to see if they are looking at the task tab so it doesn't keep changing
// back and forth between the tabs
bool change = true;
if(tabs->currentIndex() != 0)
{
change = false;
}
if(change)
{
tabs->setCurrentIndex(0);
}else if(in)
{
tabs->setCurrentIndex(0);
}
}
void TaskListProcess::replyFinished(QNetworkReply *reply)
{
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error in" << reply->url() << ":" << reply->errorString();
return;
}
QString data = reply->readAll().trimmed();
post_data = data;
if(get_task_list)
{
setTaskList();
}
}
void TaskListProcess::sendPost(QString file_name, QUrlQuery params)
{
post_data = "";
QUrl url(sci.getHost() + file_name);
url.setQuery(params);
data.clear();
data.append(params.toString().toUtf8());
request.setUrl(url);
nam->post(request, data);
}
From the Qt docs http://qt-project.org/doc/qt-5.1/qtnetwork/qnetworkaccessmanager.html
Note: After the request has finished, it is the responsibility of the
user to delete the QNetworkReply object at an appropriate time. Do not
directly delete it inside the slot connected to finished(). You can
use the deleteLater() function.
I would suggest calling reply->deleteLater() in your replyFinished() method.
You should call deleteLater() for an QNetworkReply object after use.
Note: After the request has finished, it is the responsibility of the user to delete the QNetworkReply object at an appropriate time. Do not directly delete it inside the slot connected to finished(). You can use the deleteLater() function.
More information here: http://harmattan-dev.nokia.com/docs/library/html/qt4/qnetworkaccessmanager.html
Thank you everyone for the hel.
It was very simply the "deleteLater()" on the reply in the
void replyFinished(QNetworkReply *reply)
{
}
and it should have looked like this
void replyFinished(QNetworkReply *reply)
{
// after all of your processing
reply->deleteLater();
}
it was such a small problem but one that drove me crazy for a long time so i hope this helps