This is a Qt program. I am trying to run gcc command and get the result using _popen(on Windows). However, I get no output.
After debugging, I find that gcc command runs ok.
void editor::on_action_Compile_triggered()
{
QString str = "gcc \""+curFile+"\" -o \""+outputFile+"\" 2>&1"; //compile curFile
FILE *fp = _popen(str.toStdString().data(),"r");
if (!fp)
{
ui->Log->setText("Error."); //Log is a text browser
}
else
{
QString tmpStr = "";
char tmp[1024] = { 0 };
while (fgets(tmp, 1024, fp) != NULL) //read fp
tmpStr += (QString)tmp;
ui->Log->setText(tmpStr); //print to screen
}
_pclose(fp);
}
According to me, you are not having a problem. Your above code is working for me (as long as I declare a correct curfile and outputFile). You are not having an ouput because gcc has successfully compiled the file. You may want to verify if the file called outputFile has been produced. Indeed, when gcc succeeds, it does not ouput anything.
Otherwise, you might be having a problem with your signal/slot connexion which does not trigger the slot on_action_Compile_triggered(then please read on the complete code provided below)
To test it try to modify your curFile to point to an inexisting file and you will get an ouput error typical of gcc.
To check this, as for me, I created a QmainWindow with a QPushButton button (called pushbutton) and a QtextEdit (called Log). I provide my complete code below.
When I have an error (for instance the compiled file is not found. to emulate this, rename your curFile into a wrong file), I obtain this (using your code above).
When I do not have any error, I obtain nothing in the QTextEditcontrol but the outputFile executable file is produced by gcc in the directory:
Here is my code:
// QMainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void compile();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
// QMainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QObject::connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::compile);
}
MainWindow::~MainWindow()
{
QObject::disconnect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::compile);
delete ui;
}
void MainWindow::compile()
{
QString curFile("..\\..\\T0180694\\test.c");
QString outputFile("..\\..\\T0180694\\test.exe");
//copied all from your code
QString str = "gcc \""+curFile+"\" -o \""+outputFile+"\" 2>&1"; //compile curFile
FILE *fp = _popen(str.toStdString().data(),"r");
if (!fp)
{
ui->Log->setText("Error."); //Log is a text browser
}
else
{
QString tmpStr = "";
char tmp[1024] = { 0 };
while (fgets(tmp, 1024, fp) != NULL) //read fp
tmpStr += (QString)tmp;
ui->Log->setText(tmpStr); //print to screen
}
_pclose(fp);
//until here
}
//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
Related
New to C++ and Qt as part of a research project (biology) and have been struggling with presumably some quite simple stuff. I'd really appreciate someone's help.
I'm working with a GUI for a pre-existing programme and I'm trying to transfer a QString variable from the QLineEdit of one of the windows (inputform), to the QLineEdit of a second window (output form).
The bit I'm stuck with is that I need the output form to appear, with it's LineEdit pre-populated, when I click a button on a third window (filedialog).
Problem:
At start up --> two windows appear: filedialog and inputform.
User enters data into inputform's QLineEdit
User presses 'transferButton' on filedialog window
On button press --> outputform appears, with a QLineEdit pre-populated with the user's data (from the inputform).
I assume the problem is of the getter/setter variety and my variable is probably going out of scope, but I've tried following lots of similar examples but can't make it work.
Thanks in advance.
Here's my code:
Main.cpp
#include "filedialog.h"
#include "inputform.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FileDialog w;
InputForm w2;
w.show();
w2.show();
return a.exec();
}
filedialog.h
#ifndef FILEDIALOG_H
#define FILEDIALOG_H
#include <QDialog>
namespace Ui {
class FileDialog;
}
class FileDialog : public QDialog
{
Q_OBJECT
public:
explicit FileDialog(QWidget *parent = nullptr);
~FileDialog();
void setFileName();
QString getFileName();
private slots:
void on_transferButton_clicked();
private:
Ui::FileDialog *ui;
QString fileName;
};
#endif // FILEDIALOG_H
filedialog.ccp
#include "filedialog.h"
#include "ui_filedialog.h"
#include "inputform.h"
#include "ui_inputform.h"
#include "outputform.h"
#include "ui_outputform.h"
FileDialog::FileDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::FileDialog)
{
ui->setupUi(this);
}
FileDialog::~FileDialog()
{
delete ui;
}
void FileDialog::setFileName()
{
InputForm *inputform = new InputForm;
fileName = inputform->ui->inputLineEdit->text();
}
QString FileDialog::getFileName()
{
return fileName;
}
void FileDialog::on_transferButton_clicked()
{
setFileName();
OutPutForm *outputform = new OutPutForm;
outputform->ui->outputLineEdit->setText(getFileName());
outputform->show();
}
inputform.h
#ifndef INPUTFORM_H
#define INPUTFORM_H
#include <QWidget>
namespace Ui {
class InputForm;
}
class InputForm : public QWidget
{
Q_OBJECT
public:
explicit InputForm(QWidget *parent = nullptr);
~InputForm();
Ui::InputForm *ui;
};
#endif // INPUTFORM_H
inputform.ccp
#include "inputform.h"
#include "ui_inputform.h"
InputForm::InputForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::InputForm)
{
ui->setupUi(this);
}
InputForm::~InputForm()
{
delete ui;
}
outputform.h
#ifndef OUTPUTFORM_H
#define OUTPUTFORM_H
#include <QWidget>
namespace Ui {
class OutPutForm;
}
class OutPutForm : public QWidget
{
Q_OBJECT
public:
explicit OutPutForm(QWidget *parent = nullptr);
~OutPutForm();
Ui::OutPutForm *ui;
};
#endif // OUTPUTFORM_H
outputform.ccp
#include "outputform.h"
#include "ui_outputform.h"
OutPutForm::OutPutForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::OutPutForm)
{
ui->setupUi(this);
}
OutPutForm::~OutPutForm()
{
delete ui;
}
Thank you for your brief pointer.
After some playing around:
Setup mainwindow (or in my case main dialog window). Generate inputform instance, connect button to inputform.
FileDialog::FileDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::FileDialog)
{
ui->setupUi(this);
InputForm *inputForm = new InputForm;
connect(ui->transferButton,SIGNAL(clicked()),inputForm,SLOT(getLineEditTextFunc()));
inputForm->show();
}
FileDialog::~FileDialog()
{
delete ui;
}
void FileDialog::on_transferButton_clicked()
{
}
Then from the input form:
Define a function to get the input form's LineEdit text (fileName); and then also generate an output form and populate it's LineEdit with the fileName variable.
InputForm::InputForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::InputForm)
{
ui->setupUi(this);
}
InputForm::~InputForm()
{
delete ui;
}
void InputForm::getLineEditTextFunc()
{
fileName = this->ui->inputLineEdit->text();
OutPutForm *outputform = new OutPutForm;
outputform->ui->outputLineEdit->setText(fileName);
outputform->show();
}
I have modified the Text Finder example which I got from a Qt Tutorial and made a Text Viewer. In this program, the user types in the address of the file and clicks the Search button. The program then displays the content of the text file. Below is my code.
text_finder.cpp:
#include "text_finder.h"
#include "ui_text_finder.h"
#include <QHBoxLayout>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
Text_Finder::Text_Finder(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Text_Finder)
{
ui->setupUi(this);
}
Text_Finder::~Text_Finder()
{
delete ui;
}
void Text_Finder::loadFile(QFile file){ // I have to pass the file name as parameter.
QFile inputFile(file);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString line = in.readAll();
inputFile.close();
ui->read->setText(line);
QTextCursor cursor = ui->read->textCursor();
cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1);
}
void Text_Finder::on_search_clicked()
{
// Code that gets the path from the text box.
loadFile();//Parameters not passed yet.
}
I have not yet entered the code which gets the name of the file from the address of the text box. I will have to pass the file to the loadFile() function which will enter the contents into the Text Edit in the center of the program. I want a solution to get the name of the file of which the user enters. For example, the user might enter, "/home/user/input.txt". The program should get the contents of that file and forward it to loadFile(). An solution with an explanation on how the various parts work is needed. I am using Qt Creator on Ubuntu 15.04 (Beta).
If i understand you correctly, the user types the full path or address of the file in the text box and you want to get just the name of the file out of the full path the user entered.
EDIT: I realized using 'QFileDialog' was the ideal way to get the file name. So this
is how i redesigned the whole code;
text_finder.h
#ifndef TEXT_FINDER_H
#define TEXT_FINDER_H
#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
class Text_Finder : public QWidget{
Q_OBJECT
public:
Text_Finder(QWidget *parent = 0);
~Text_Finder();
public slots:
void on_search_clicked();
void open();
//void loadFile(QString const &filename);
private:
void loadFile(QString const &filename);
QLineEdit *txtFileName;
QTextEdit *txtFileContents;
QString fileName;
QPushButton *search;
QPushButton *openFile;
};
#endif
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
};
#endif // MAINWINDOW_H
text_finder.cpp
#include "text_finder.h"
Text_Finder::Text_Finder(QWidget *parent) : QWidget(parent) {
openFile = new QPushButton("Open File");
connect(openFile, SIGNAL(clicked()), this, SLOT(open()));
txtFileName = new QLineEdit;
search = new QPushButton("&Search");
txtFileContents = new QTextEdit;
QHBoxLayout *dialogAndViewLayout = new QHBoxLayout;
dialogAndViewLayout->addWidget(openFile);
dialogAndViewLayout->addWidget(txtFileName);
dialogAndViewLayout->addStretch();
dialogAndViewLayout->addWidget(search);
QVBoxLayout *layout = new QVBoxLayout;
layout->addLayout(dialogAndViewLayout);
layout->addWidget(txtFileContents);
connect(search, SIGNAL(clicked()), this, SLOT(on_search_clicked()));
setLayout(layout);
}
Text_Finder::~Text_Finder(){
delete txtFileName;
delete txtFileContents;
delete search;
delete openFile;
}
void Text_Finder::loadFile(QString const &filename){
QFile inputFile(filename);
inputFile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream textStream(&inputFile);
QString contents = textStream.readAll();
inputFile.close();
txtFileContents->setPlainText(contents);
}
void Text_Finder::on_search_clicked() {
loadFile(fileName);
}
/*this slot opens a file dialog. After the file has been selected, it sets
the file to the text text edit box*/
void Text_Finder::open() {
fileName = QFileDialog::getOpenFileName(this, "Open text", "/home/",
"");
txtFileName->setText(fileName);
}
mainwindow.cpp
#include "mainwindow.h"
#include "text_finder.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
Text_Finder *textFinder = new Text_Finder;
setCentralWidget(textFinder);
}
MainWindow::~MainWindow() {
}
Finally
main.cpp
#include "text_finder.h"
#include <QApplication>
int main(int argc, char **argv){
QApplication app(argc, argv);
Text_Finder *window = new Text_Finder;
window->show();
return app.exec();
}
Unless you're going to do some programmatic editing, you do not need to use QTextCursor at all.
I suggest you have a browse through the reference manual before trying to carry on since it's clear that you are not familiar with the bare-basics of the graphical widgets you're using.
If you're only reading in a file name and then displaying the contents in plain text format, this is all you need to do. (I'm assuming your filename is entered into a QLineEdit widget and ui->read is a QTextEdit widget)
void Text_Finder::loadFile(QString const &filename){ // I have to pass the file name as parameter.
QFile inputFile(filename);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString contents = in.readAll();
inputFile.close();
ui->read->setPlainText(contents);
}
void Text_Finder::on_search_clicked()
{
QString filename = ui->filename->text();
loadFile(filename);
}
EDIT:
I've created a fully-functional remake of your code, incorporating the changes I suggested. I have compiled and tested it and it is working as per your description.
Note: In the absence of your UI file, I've created the user interface manually.
text_finder.h
#ifndef TEXT_FINDER_H
#define TEXT_FINDER_H
#include <QMainWindow>
class QLineEdit;
class QTextEdit;
class Text_Finder : public QMainWindow{
Q_OBJECT
public:
Text_Finder(QWidget *parent = 0);
~Text_Finder();
public slots:
void on_search_clicked();
private:
void loadFile(QString const &filename);
QLineEdit *txtFileName;
QTextEdit *txtFileContents;
};
#endif // TEXT_FINDER_H
main.cpp
#include "text_finder.h"
#include <QApplication>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
Text_Finder::Text_Finder(QWidget *parent) :
QMainWindow(parent)
{
QWidget *ui = new QWidget(this);
QHBoxLayout *hLayout = new QHBoxLayout;
txtFileName = new QLineEdit(this);
QPushButton *loadButton = new QPushButton("Load File", this);
connect(loadButton, &QPushButton::clicked, this, &Text_Finder::on_search_clicked);
hLayout->addWidget(txtFileName);
hLayout->addWidget(loadButton);
QVBoxLayout *vLayout = new QVBoxLayout(this);
vLayout->addLayout(hLayout);
txtFileContents = new QTextEdit(this);
vLayout->addWidget(txtFileContents);
ui->setLayout(vLayout);
setCentralWidget(ui);
}
Text_Finder::~Text_Finder(){
// It's not necessary to explicitly delete any widgets.
// QObject implements the Composite Pattern, which takes care of all this automatically
}
void Text_Finder::loadFile(QString const &filename){
QFile inputFile(filename);
inputFile.open(QIODevice::ReadOnly);
QTextStream in(&inputFile);
QString contents = in.readAll();
inputFile.close();
txtFileContents->setPlainText(contents);
}
void Text_Finder::on_search_clicked()
{
QString filename = txtFileName->text();
loadFile(filename);
}
int main(int argc, char **argv){
QApplication app(argc, argv);
Text_Finder w;
w.show();
return app.exec();
}
HINT for future questions: You will get better answers quicker if you include an SSCCE in your question. What I've included in this edit is a suitable example.
I have the MainWindow class. In the constructor of this class I want to start a new thread that will do some work. But I get this error:
Assert failure in QWidget: "Widgets must be created in the GUI thread."
In this new thread I am not creating any widgets. This is what I have tried so far. Could someone help me on solving this problem? In don't have experience with signals and slots and I will really appreciate some advises.
newThread.h
#ifndef NEWTHREAD_H
#define NEWTHREAD_H
#include <QThread>
#include "mainwindow.h"
class NewThread : public QThread
{
Q_OBJECT
public:
explicit NewThread(QObject *parent = 0);
signals:
public slots:
protected:
void run();
};
#endif // NEWTHREAD_H
newThread.cpp
#include "newthread.h"
NewThread::NewThread(QObject *parent) :
QThread(parent) { }
void NewThread::run(){
MainWindow m;
m.updateInBackground();
}
MainWindow.cpp
MainWindow::MainWindow(QStringList applications, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ReadFromRegistry read;
this->setFixedSize(435,280);
ui->setupUi(this);
appsNames = applications;
this->apps = read.getApplicationsFromRegistry(appsNames);
ui->updateInBackgroundCkb->setChecked(false);
//read from settings.xml the time interval
QString time = RWXml::readSettingsFile();
if(time.compare("-1") != 0){
NewThread th;
while(true){
th.start();
th.sleep(time.toLong(0,10));
}
}
}
EDIT:
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStringList apps;
QString app = "AppTest1";
apps.append(app);
app = "AppTest2";
apps.append(app);
app = "AppTest3";
apps.append(app);
MainWindow w(apps);
w.create();
w.show();
return a.exec();
}
I instantiate the MainWindow in main. But i need to access the method from MainWindow in the run method of the NewThread. That's why it is instantiated in the NewThread.
EDIT:
void MainWindow::updateInBackground(){
ClientSocket client;
for(Application ap : getApps()){
QString currentVersion = ap.getAppVersion();
QString appCode = ap.getAppCode();
QString appSerial = ap.getAppSerialNo();
client.connect();
QString message = "2//" + currentVersion + "//" + appCode + "//"+ appSerial;
//send message to the server
client.sendMessage(message);
//receiver message from the server
QString received = client.receiveMessage();
//check if the current version is the last one
if(received.compare("0") != 0){
//if is not the last one, set the new version
ap.setAppVersion(received);
//set the update date
ap.setCurrentDate();
//write in windows registry
WriteInRegistry::writeRegistry(ap);
//update the xml file containg the updates of this application
updateXMLFile(ap);
}
}
//read from registry
ReadFromRegistry read;
//populate the grid from the MainWindow with the new data
populateTable(read.getApplicationsFromRegistry(getAppsNames()));
client.closeConnection();
}
Your issue with your code is that you create the mainwindow and the qt application in different threads. The main window seems to be created in your "new thread", whereas the qt application is not.
You also seem to have a circular dependency between the mainwindow constructor and the run method of the thread.
You would need to move the mainwindow creation into your main.cpp which is also a logical place for it.
That being said, please do take a look at the url below and all the references in the post for getting some further thoughts.
How to Use QThread in the Right Way (Part 1)
How to Use QThread in the Right Way (Part 2)
I want to try QWinThumbnailToolBar in Qt 5.2 but it doesn't work !(Program runs but there is no thumbnail !!!!)
//main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QWinThumbnailToolButton>
#include <QWinThumbnailToolBar>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QWinThumbnailToolBar* thumbnailToolBar;
QWinThumbnailToolButton *playToolButton;
QWinThumbnailToolButton *forwardToolButton;
QWinThumbnailToolButton *backwardToolButton;
};
#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);
thumbnailToolBar = new QWinThumbnailToolBar(this);
thumbnailToolBar->setWindow(this->windowHandle());
playToolButton = new QWinThumbnailToolButton(thumbnailToolBar);
playToolButton->setEnabled(false);
playToolButton->setToolTip(tr("true"));
playToolButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
forwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar);
forwardToolButton->setEnabled(true);
forwardToolButton->setToolTip(tr("Fast forward"));
forwardToolButton->setIcon(style()->standardIcon(QStyle::SP_TrashIcon));
backwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar);
backwardToolButton->setEnabled(true);
backwardToolButton->setToolTip(tr("Rewind"));
backwardToolButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekBackward));
thumbnailToolBar->addButton(backwardToolButton);
thumbnailToolBar->addButton(playToolButton);
thumbnailToolBar->addButton(forwardToolButton);
}
MainWindow::~MainWindow()
{
delete ui;
}
//pro file :
QT += core gui winextras multimedia
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = untitled1
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
I think the problem is with these two line :
thumbnailToolBar = new QWinThumbnailToolBar(this);
thumbnailToolBar->setWindow(this->windowHandle());
I also tried to use QWidget instead of QMainWindow...
How can I fix it ??
Your code to create QWinThumbnailToolBar is correct, the problem is where you create it. I think creating it in the window constructor is the problem (Maybe because the window handle is not ready yet). You can make something like this:
// main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FrmMain w;
w.show();
w.createThmbBar();
return a.exec();
}
Where createThumbBar() is a public function where you create the QWinThumbnailToolBar as in:
// MainWindow.cpp
void MainWindow::createThmbBar()
{
thumbnailToolBar = new QWinThumbnailToolBar(this);
thumbnailToolBar->setWindow(this->windowHandle());
playToolButton = new QWinThumbnailToolButton(thumbnailToolBar);
playToolButton->setEnabled(false);
playToolButton->setToolTip(tr("true"));
playToolButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
forwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar);
forwardToolButton->setEnabled(true);
forwardToolButton->setToolTip(tr("Fast forward"));
forwardToolButton->setIcon(style()->standardIcon(QStyle::SP_TrashIcon));
backwardToolButton = new QWinThumbnailToolButton(thumbnailToolBar);
backwardToolButton->setEnabled(true);
backwardToolButton->setToolTip(tr("Rewind"));
backwardToolButton->setIcon(style()->standardIcon(QStyle::SP_MediaSeekBackward));
thumbnailToolBar->addButton(backwardToolButton);
thumbnailToolBar->addButton(playToolButton);
thumbnailToolBar->addButton(forwardToolButton);
}
Late answer but hopefully it could help anyone faces the same issue later.
The fix that #Ramez proposed works however I am getting a crash on application shutdown due to the windows extra. Is there something special I need to do myself in the destructor? The QWindow has already been deleted when the QWinThumbnailToolBarPrivate::hasHandle() checks for the handle.
Exception thrown: read access violation.
d was 0xFFFFFFFFFFFFFF7F.
QPlatformWindow *QWindow::handle() const
{
Q_D(const QWindow);
return d->platformWindow;
}
Stack Trace Below:
Qt5Guid.dll!QWindow::handle() Line 1929 C++
Qt5WinExtrasd.dll!QWinThumbnailToolBarPrivate::hasHandle() Line 460 C++
Qt5WinExtrasd.dll!QWinThumbnailToolBarPrivate::handle() Line 465 C++
Qt5WinExtrasd.dll!QWinThumbnailToolBarPrivate::nativeEventFilter(const QByteArray & __formal, void * message, long * result) Line 549 C++
Qt5Cored.dll!QAbstractEventDispatcher::filterNativeEvent(const QByteArray & eventType, void * message, long * result) Line 484 C++
[External Code]
Qt5Guid.dll!QWindowPrivate::destroy() Line 1914 C++
Qt5Guid.dll!QWindow::destroy() Line 1864 C++
Qt5Widgetsd.dll!QWidgetPrivate::deleteTLSysExtra() Line 1891 C++
Qt5Widgetsd.dll!QWidget::destroy(bool destroyWindow, bool destroySubWindows) Line 12515 C++
Qt5Widgetsd.dll!QApplication::~QApplication() Line 798 C++
I have been working on a Qt Creator application, and just recently ran into a run-time error that I have no idea how to find and fix. The program just unexpectedly finishes once it starts up, and when I run the debug, it gives me the error:
The inferior stopped because it
received a signal from the operating
system.
Signal name: SIGSEGV
Signal meaning: Segmentation fault
Now I understand that this error is caused by attempted access to an invalid memory location, but I have absolutely no clue what I did to trigger it. The debugger seems to be pointing me to a specific line of code:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QString>
#include "ui_mainwindow.h"
#include "foamdata.h"
#include "domaingeneration.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
int getXDim() const { return ui->xDim->value(); } // THIS is where it points to!!
int getYDim() const { return ui->yDim->value(); }
private slots:
void on_findDir_clicked();
void on_create_clicked();
void on_generateDomain_clicked();
private:
Ui::MainWindow *ui;
DomainGeneration dg; //declaring second window as a member of main window
};
#endif // MAINWINDOW_H
That function is used in this:
#include "domaingeneration.h"
#include "ui_domaingeneration.h"
#include <QCheckBox>
#include "mainwindow.h"
DomainGeneration::DomainGeneration(QWidget *parent) :
QDialog(parent),
ui(new Ui::DomainGeneration)
{
ui->setupUi(this);
// Generating checkboxes for domain generation
MainWindow* main;
int x_dim = main->getXDim();
int y_dim = main->getYDim();
QVector<QCheckBox*> checkBoxVector;
for(int i = 0; i < x_dim; ++i){
for(int j = 0; j < y_dim; ++j){
checkBoxVector.append(new QCheckBox(this));
checkBoxVector.last()->setGeometry(i * 20, j * 20, 20, 20);
}
}
}
DomainGeneration::~DomainGeneration()
{
delete ui;
}
Here is the mainwindow source code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "functions.h"
#include "main.cpp"
#include <QtGui/QApplication>
#include <QFileDialog>
#include <fstream>
#include "foamdata.h"
#include "domaingeneration.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
// This is the function that handles the directory search when the 'browse' button is pressed
void MainWindow::on_findDir_clicked()
{
QString path; //declaring the path to the base directory
path = QFileDialog::getExistingDirectory( //gathering the directory from QFileDialog class
this, tr("Choose the project directory"),
"/home",
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks );
ui->baseDir->setText( path ); //setting the retrieved path into the line edit box
}
// This function makes the project by creating a new directory with name 'project_name'
// in the base directory, and collects the OpenFOAM version number and simulation type
void MainWindow::on_create_clicked()
{
QString project_name, foam_version, full_dir, slash, base_dir;
base_dir = ui->baseDir->text();
project_name = ui->projectName->text(); //getting the text from the 'projectName' field
foam_version = ui->version->currentText(); //getting the selection from the 'version' drop-down box
project_info.save_version(foam_version); //saving data in a global project variable
project_info.save_projName(project_name);
project_info.save_simType(ui->simType->currentText());
//first checking if the fields have input in them:
QString blank = "";
QString no_text0 = "Please enter project name";
if( project_name==no_text0 || (project_name==blank) ) {
ui->projectName->setText( no_text0 );
return;
}
QString no_text1 = "Please enter a valid directory";
if( base_dir==no_text1 || base_dir==blank || !QDir( base_dir ).exists() ) {
ui->baseDir->setText( no_text1 );
return;
}
slash = "/"; // needed to separate folders in the directory (can't use a literal)
full_dir = base_dir.append(slash.append(project_name));
project_info.save_directory(full_dir);
if( !QDir(full_dir).exists() ) //check if directory already exists
QDir().mkdir(full_dir); //creating directory
QString blockmesh_filename, suffix;
suffix = "_blockMeshDict";
slash = "/"; //must re-define
blockmesh_filename = full_dir.append( slash.append( project_name.append(suffix) ) );
std::ofstream create_file( blockmesh_filename.toStdString().c_str() ); //creating empty blockmesh file
}
void MainWindow::on_generateDomain_clicked() //opening the new window for domain generation
{
dg.show();
}
Can anybody help me find what the heck is going on?
The obvious is that you're not initializing MainWindow * main;:
MainWindow* main; // right here
int x_dim = main->getXDim();
int y_dim = main->getYDim();
There might, however, be other uninitialized values, the piece of code presented doesn't really say much.
Or here:
// Generating checkboxes for domain generation
MainWindow* main;
int x_dim = main->getXDim();
int y_dim = main->getYDim();
main definitely doesn't point anywhere!
You have a private data member ui in class MainWindow that is NULL. That variable is never set. In fact, there is no no way to set it. (Where is the setter?)