I'm trying to add a save as feature to a simple text editor I'm making with C++ and QT. I'm attempting to close the current tab when you save your file and open a new tab with the same index and has the name of the new file as the tab title. This is my code:
QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), "", tr("All Files (*)"));
if (fileName.isEmpty())
return;
else
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly))
{
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());
return;
}
QTextStream out (&file);`
out << ui->plainTextEdit->toPlainText();
QFileInfo FileData(file);
int currentTab = ui->tabWidget->currentIndex();
ui->tabWidget->removeTab(currentTab);
QTextStream InputData(&file);
ui->tabWidget->insertTab(currentTab, new Form(), FileData.fileName());
ui->tabWidget->setCurrentIndex(currentTab);
ui->plainTextEdit->setPlainText(InputData.readAll());
file.flush();
file.close();
}
When I try to save the new file, it saves the file to the selected location and replaces the current tab with the file name, but it doesn't write the file to the text window. Any help would be great.
Here is my demo code and it seems to work:
form.cpp which has a plainTextEdit
#include "form.h"
#include "ui_form.h"
Form::Form(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form)
{
ui->setupUi(this);
}
Form::~Form()
{
delete ui;
}
QString Form::GetText()
{
return ui->plainTextEdit->toPlainText();
}
void Form::SetText(QString text)
{
ui->plainTextEdit->setPlainText(text);
}
And the mainwindow.cpp which contains a QTabWidget
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "form.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
ui->tabWidget->insertTab(0, new Form(), "My File");
ui->tabWidget->setCurrentIndex(0);
}
void MainWindow::on_pushButton_2_clicked()
{
int currentIndex = ui->tabWidget->currentIndex();
//Save the text to a file or a variable...
QString content = static_cast<Form*>(ui->tabWidget->widget(currentIndex))->GetText();
ui->tabWidget->removeTab(currentIndex);
ui->tabWidget->insertTab(currentIndex, new Form(), "Saved File");//new name
static_cast<Form*>(ui->tabWidget->widget(currentIndex))->SetText(content);
ui->tabWidget->setCurrentIndex(currentIndex);
}
It is working for me, please try.
Thank You.
Related
I wanted to open QFileDialog for a specific path like //DC1/C$/Users/ but when QFileDialog opens it goes to a default path. When QFileDialog opens, I can change directory to the UNC path but I wanted to open this path as default. How can I do that? In the following code, g_absolutePath has been initialized with //DC1/C$/Users/ but it doesn't work.
#include "uploadfm.h"
#include "ui_uploadfm.h"
#include "mainwindow.h"
UploadFM::UploadFM(QWidget *parent) : QMainWindow(parent), ui(new Ui::UploadFM)
{
ui->setupUi(this);
QWidget::setFixedSize(600, 175);
}
UploadFM::~UploadFM()
{
delete ui;
}
void UploadFM::on_pushButtonSource_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, "Choose File", g_absolutePath);
if(fileName.isEmpty())
return;
ui->lineEditSourcePath->setText(fileName);
}
void UploadFM::on_pushButtonDestination_clicked()
{
QString fileName = QFileDialog::getExistingDirectory(this, "Choose Folder", g_absolutePath);
if(fileName.isEmpty())
return;
ui->lineEditDestinationPath->setText(fileName);
}
void UploadFM::on_pushButtonUpload_clicked()
{
QString l_sourceFileName = ui->lineEditSourcePath->text();
QString l_destinationFileName = ui->lineEditDestinationPath->text();
if(l_sourceFileName.isEmpty() || l_destinationFileName.isEmpty())
return;
QFile file(l_sourceFileName);
if(file.copy(l_destinationFileName))
{
statusBar()->showMessage("Upload has been Successful ... ");
}
else
{
statusBar()->showMessage("Upload has failed ...");
}
}
The Qt Documentation documents how to do this :
void UploadFM::on_pushButtonDestination_clicked()
{
const QString defaultPath = "//DC1/blabla...";
QString fileName = QFileDialog::getExistingDirectory(this, "Choose Folder", g_absolutePath, defaultPath);
...
}
I'm trying to open the file explorer dialog from a dialog window using Qt and C++. My "dialog.cpp" file looks like this:
#include "dialog.h"
#include "ui_dialog.h"
#include "QFileDialog"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_Browse_clicked()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C://", "All files (*.*)");
}
Everywhere I have looked says that this should work without a problem. So I tried putting the same exact code in my "mainwindow.cpp" file. Which is this:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_dialog.h"
#include "QFileDialog"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_Open_dialog_clicked()
{
dialogUi.setupUi(dialog);
dialog->show();
}
void MainWindow::on_pushButton_Save_clicked()
{
QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "C://", "All Files (*.*)");
}
This opens up the file explorer dialog with no issues. However, I want to open the file explorer from the dialog window that is opened by the main window, which isn't working even though it's the same exact code. I even added a new MainWindow class ("mainwindow2.cpp") and tried from that to see if maybe it was the Dialog class causing an issue, but the file explorer wouldn't open from that either. It only seems to work from the primary MainWindow class. (By this I mean any window opened from "mainwindow.cpp" cannot open a file explorer dialog, but "mainwindow.cpp" can open the explorer)
I'm trying to create a simple app which allows user to enter a word and the app will output the definition. I have compiled words and definitions by making mysql database file. I thought using MySQL would be a faster way make my app. My database looks like this:
rowed | Column1(word) | Column2(definition)
1 DNA A double-stranded,helical...
The pseudocode for this program definitely should be like this:
if(lineEdit == wordInput)
{
ui->label->setText("Display definition)
}
I just can't figure out how to do it. So far I have tried following code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDebug>
#include <QPalette>
#define Path_to_DB "/Users/makkhay/Desktop/nep_eng-2.sqlite"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Set background picture
QPixmap bkgnd("/Users/makkhay/Desktop/background.jpg");
bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
QPalette palette;
palette.setBrush(QPalette::Background, bkgnd);
this->setPalette(palette);
myDB = QSqlDatabase::addDatabase("QSQLITE");
myDB.setDatabaseName(Path_to_DB);
QFileInfo checkFile(Path_to_DB);
if(checkFile.isFile())
{
if(myDB.open())
{
ui->label->setText("The database is connected");
}
}else{
ui->label->setText("No file found!");
}
}
MainWindow::~MainWindow()
{
delete ui;
myDB.close();
}
void MainWindow::on_pushButton_clicked()
{
// QMessageBox::StandardButton reply= QMessageBox::question(this,
// "My Title", " Word not found, quit app?",
// QMessageBox::Yes | QMessageBox::No);
// if(reply == QMessageBox::Yes){
// QApplication::quit();
//}
if(!myDB.isOpen()){
qDebug() << " No connection to db";
return;
}
QString wordInput, definition;
wordInput = ui->lineEdit->text();
QSqlQuery qry;
qry.prepare("SELECT Column1,Column2 FROM Nepali WHERE Column1 = :input");
qry.bindValue(":input",wordInput);
// int fieldNo = query.record().indexof("Column1");
if(qry.exec())
{
ui->debug->setText(" Checking output!"); // output is visible
while (qry.next())
{
ui->output->setText("Checing output!"); // output is not visible
QString inputWord = qry.value(0).toString();
QString wordDefinition = qry.value(1).toString();
ui->output->setText(wordDefinition);
}
}
}
OK, the following code works for me. Try commenting out your existing code and pasting this code in. This code is basically the exact same code you posted, I just commented out some of the code to set the background and removed some excess lines.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDebug>
#include <QPalette>
#include <QSqlQuery>
#include <QFileInfo>
#define Path_to_DB "/Users/makkhay/Desktop/nep_eng-2.sqlite"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Set background picture
//QPixmap bkgnd("/Users/makkhay/Desktop/background.jpg");
//bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
//QPalette palette;
//palette.setBrush(QPalette::Background, bkgnd);
//this->setPalette(palette);
myDB = QSqlDatabase::addDatabase("QSQLITE");
myDB.setDatabaseName(Path_to_DB);
QFileInfo checkFile(Path_to_DB);
if(checkFile.isFile())
{
if(myDB.open())
{
ui->label->setText("The database is connected");
}
}else{
ui->label->setText("No file found!");
}
}
MainWindow::~MainWindow()
{
delete ui;
myDB.close();
}
void MainWindow::on_pushButton_clicked()
{
if(!myDB.isOpen()){
qDebug() << " No connection to db";
return;
}
QString wordInput;
wordInput = ui->lineEdit->text();
QSqlQuery qry;
qry.prepare("SELECT Column1,Column2 FROM Nepali WHERE Column1 = :input");
qry.bindValue(":input",wordInput);
if(qry.exec())
{
ui->debug->setText(" Checking output!");
while (qry.next())
{
// Retrieve Values from select statement
QString inputWord = qry.value(0).toString();
QString wordDefinition = qry.value(1).toString();
// Display values
ui->output->setText(wordDefinition);
}
} else {
qDebug() << "query failed to execute";
}
}
After declaring the qry variable the code should look like this:
qry.prepare("SELECT Column1,Column2 FROM tableName WHERE Column1 = :input");
qry.bindValue(":input",wordInput);
if(qry.exec())
{
if (qry.next())
{
// Extract the results from the SELECT statement
QString inputWord = qry.value(0).toString();
QString wordDefinition = qry.value(1).toString();
// Then use the values for whatever you wish.
}
}
You don't need comma before WHERE. Also, I guess that you are comparing Column1 with wordInput, not Column2.
if(qry.exec("SELECT Column1,Column2 FROM some_table WHERE Column1='"+ wordInput+"'"))
Edit: you don't mention a table you are selecting from.
In my Windows forms code, ui is used to define graphical element by default. But I want to modify them in a function, like this:
The problems is that the debug tool tells me that ui is not declared in this scope.
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "datawindow.h"
void getData(ui){
QFile inputFile("C:\\pepoles.txt");
if (inputFile.open(QIODevice::ReadOnly)){
QTextStream in(&inputFile);
while ( !in.atEnd() ){
QString line = in.readLine();
ui->listWidgetData->addItem(line);
}
}
else{
QMessageBox::critical(this, "Erreur", "Une erreur s'est produite :(");
}
inputFile.close();
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
getData(ui);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionNouvellesDonnees_triggered() {
w.show();
}
void getData(ui){
That line starts definition of getData function, which takes one variable, with type ui and no name (so it can't be accessed in the function code).
Add type...
void getData(MainWindow::Ui *ui){
Make getData() a member of MainWindow:
void MainWindow::getData()
{
QFile inputFile("C:\\pepoles.txt");
if (inputFile.open(QIODevice::ReadOnly)) {
QTextStream in(&inputFile);
while ( !in.atEnd() ) {
QString line = in.readLine();
ui->listWidgetData->addItem(line);
}
} else {
QMessageBox::critical(this, "Erreur", "Une erreur s'est produite :(");
}
inputFile.close();
}
Then, in your constructor:
ui->setupUi(this);
getData();
I recommend this approach since ui contains private members, so it's best to have a member function modify it.
Don't forget to declare getData() in the header file of your MainWindow class. You should probably make it private.
And btw, ui is not an array. It's an object pointer.
This is the main window so far and the second window is a dialog window. How do I get the text from a textbox on window2 when it closes?
Thanks.
#include "mainwindow.h"
#include "window2.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(closeProgram()));
connect(ui->openWindowBtn, SIGNAL(clicked()), this, SLOT(openSecondWindow()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::openSecondWindow()
{
Window2 w2;
w2.exec();
}
void MainWindow::closeProgram()
{
close();
}
Found Solution
All I had to do is create a getString() function in the Window2 class to retreive the text from ui->...
QString Window2::getString()
{
return ui->textEdit->text();
}
Look at your .ui file in designer (or the resulting generated file from the uic), and access the QLineEdit object by name (the same way you connect that signal). You can retrieve the text with the lineEdit::text() accessor.