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);
...
}
Related
I want to display my image in a new window . So i am trying to pass the path of the image as value through constructor
void DicomWidget::mouseDoubleClickEvent(QMouseEvent *event){
qDebug() << ui->diWidget->whatsThis();
QString path = ui->diWidget->whatsThis();
EditWindow * editWindow = new EditWindow(this);
editWindow->setWindowTitle(path);
editWindow->setWhatsThis(path);
editWindow->show();
}
I want to pass the path in constructor but if I do the UI of the editwindow is not rendering
my editwindow.cpp
#include "editwindow.h"
#include "ui_editwindow.h"
EditWindow::EditWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::EditWindow)
{
ui->setupUi(this);
}
EditWindow::~EditWindow()
{
delete ui;
}
//Here i need to have refernce to this how shoul i give it
EditWindow::EditWindow(QString& filepath){
QFile file (filepath);
QFileInfo fileInfo(file.fileName());
QString filename(fileInfo.fileName());
QString name = filename;
currentDicomPath = filepath;
}
void EditWindow::on_pushButton_clicked()
{
currentDicomPath = EditWindow::windowTitle();
qDebug() <<"Hello9" << currentDicomPath;
}
By rewriting the constructor with EditWindow::EditWindow(QString& filepath) the Qt constructor with EditWindow::EditWindow(QWidget *parent) won't run, and thus you can't see any rendering.
Consider amending the existing constructor with something like EditWindow::EditWindow(QWidget *parent, QString& filepath) and add your custom code below ui->setup(this);
After that, you are able to initiate your class with EditWindow* editWindow = new EditWindow(this, filepath);
Otherwise, you just created an overload of the existing constructor.
I am trying to use QProcess to call 7z.exe and unzip all *.zip and *.7z files in a root directory and subdirectories, but it works only in the root directory.
It looks like it also does not have a problem finding the right path to the next archive, but it did not unzip the file.
Output:
QProcess::start: Process is already running
Can someone help me with this problem?
My code:
mainwindows.h:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(&unzip,&QProcess::readyReadStandardOutput,this,&MainWindow::readyReadStandardOutput);
connect(&unzip,&QProcess::stateChanged,this,&MainWindow::statusChanged);
connect(ui->startButton,&QPushButton::clicked,this,&MainWindow::startClicked);
connect(&unzip,&QProcess::errorOccurred,this,&MainWindow::processError);
connect(&unzip, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),this,&MainWindow::processFinished);
connect(ui->selectPath,&QPushButton::clicked,this,&MainWindow::selectPathClicked);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::statusChanged(QProcess::ProcessState state){
switch (state) {
case QProcess::NotRunning:
ui->startButton->setText("START");
this->updateUi(true);
break;
case QProcess::Running:
case QProcess::Starting:
ui->startButton->setText("STOP");
this->updateUi(false);
}
}
void MainWindow::updateUi(bool enable)
{
ui->pathEdit->setEnabled(enable);
}
void MainWindow::startClicked()
{
qDebug()<<"Started";
QStringList arguments;
QString path=ui->pathEdit->text();
arguments<<"x"<<path+QDir::separator()+"*.zip"<<"-o"+path+QDir::separator()+"*";
switch (unzip.state()) {
case QProcess::NotRunning:
unzip.setWorkingDirectory(QCoreApplication::applicationDirPath());
unzip.start("7z.exe",arguments);
break;
case QProcess::Running:
case QProcess::Starting:
unzip.kill();
break;
}
}
void MainWindow::readyReadStandardOutput(){
ui->logTextEdit->appendPlainText(unzip.readAllStandardOutput());
}
void MainWindow::processError(QProcess::ProcessError error)
{
QMessageBox::critical(this,"Unzip warpper",tr("Error %1 has occured").arg(error));
}
void MainWindow::processFinished(int exitCode, QProcess::ExitStatus exit)
{
switch (exit) {
case QProcess::CrashExit:
QMessageBox::critical(this,"Unzip warpper",tr("Unzip process has crashed"));
break;
case QProcess::NormalExit:
break;
}
if(ui->checkRecursive->isChecked()){
QString path=ui->pathEdit->text();
QDirIterator it(path, QStringList() << "*.zip" << ".7z" ,QDir::Files, QDirIterator::Subdirectories);
while(it.hasNext()){
QString path=it.next();
qDebug()<<path;
qDebug()<<exitCode;
QStringList arguments;
arguments<<"x"<<path+QDir::separator()+"*.zip"<<"-o"+path+QDir::separator()+"*";
unzip.start("7z.exe",arguments);
}
}
}
void MainWindow::selectPathClicked()
{
QString directory = QFileDialog::getExistingDirectory(this,
tr("Select Direcory to unzip"), "");
if(!directory.isEmpty()){
ui->pathEdit->setText(directory);
}
}
void MainWindow::on_actionQuit_triggered()
{
unzip.kill();
QApplication::quit();
}
I'm currently working on a Qt Widget (using Qt 6.3) that plays audio and shows a progressbar. But I'm struggling to find a way to connect the audio progress value with the progress bar status.
Here's my code:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
mMediaPlayer = new QMediaPlayer(this);
audio_output = new QAudioOutput(this);
//this is the part I need help with
connect(mMediaPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64)));
void MainWindow::on_Button_open_media_clicked()
{
QString file_name = QFileDialog::getOpenFileName(this, "Open");
if(file_name.isEmpty()){
return;
}
mMediaPlayer->setSource(QUrl::fromLocalFile(file_name));
mMediaPlayer->setAudioOutput(audio_output);
audio_output->setVolume(ui->volume_slider->value());
on_play_button_clicked();
}
void MainWindow::on_stop_button_clicked()
{
mMediaPlayer->stop();
}
void MainWindow::on_pause_button_clicked()
{
mMediaPlayer->pause();
}
void MainWindow::on_play_button_clicked()
{
audio_output->setVolume(100);
mMediaPlayer->play();
}
void MainWindow::on_mute_button_clicked()
{
if(ui->mute_button->text() == "Mute"){
audio_output->setMuted(true);
ui->mute_button->setText("Unmute");
}
else{
audio_output->setMuted(false);
ui->mute_button->setText("Mute");
}
}
void MainWindow::on_volume_slider_valueChanged(int value)
{
audio_output->setVolume(value);
}
}
I couldn't find a way to do it using the documentation. It might be simple, but I need help.
Any help is gladly appreciated.
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.
I am new in Qt and I need to do a program who export html page to PDF
So, the main idea is use QWebPage for interpret html and export itself to pdf with QPrinter.
I have two class webview who use QWebPage and Print who use QPrinter.
In main.cpp I have connect LoadFinished to PrintPDF slot:
Print *pdf = new Print(args);
webview *nav = new webview();
nav->setPrinter(pdf->getPrinter());
if(nav->load(args) == false) {
qDebug() << "can't load page";
return 0;
}
//when the page page is ready, we will print it
QObject::connect(nav->getFrame(), SIGNAL(loadFinished(bool)), nav, SLOT(printPDF(bool)));
My webview.cpp class:
#include "webview.h"
webview::webview()
{
page = new QWebPage;
printer = 0;
}
webview::~webview()
{
delete page;
}
bool webview::load(Arguments *args)
{
QRegularExpression url("^(file|http)://");
QRegularExpression fullPath("^/");
QRegularExpressionMatch pathMatch = fullPath.match(args->getSource());
QRegularExpressionMatch urlMatch = url.match(args->getSource());
// see http://qt-project.org/doc/qt-4.8/qwebsettings.html#WebAttribute-enum for more informations
page->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
page->settings()->setAttribute(QWebSettings::AutoLoadImages, true);
page->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
page->settings()->setAttribute(QWebSettings::PrintElementBackgrounds, true);
page->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
if(pathMatch.hasMatch()) {
page->mainFrame()->load(QUrl::fromLocalFile(args->getSource()));
} else {
if (urlMatch.hasMatch()) {
page->mainFrame()->load(QUrl(args->getSource()));
} else {
fprintf(stderr, "%s\n", qPrintable(QApplication::translate("main", "Error: Invalide source file")));
return false;
}
}
return true;
}
void webview::printPDF(bool ok)
{
if(ok == true) {
qDebug() << "okay";
} else
qDebug() << "non okay";
if(printer != 0)
page->mainFrame()->print(printer);
}
This is what my console display:
non okay
QPainter::begin: A paint device can only be painted by one painter at a time.
I have no idea where the error might be due. The whole project is here
The arguments are:
./htmltopdf http://stackoverflow.com destinationFolder
(destinationFolder is not yet implemented, you must directly modify the source code)
You have more than one Painter in your Code. Search for it.
I thing the Problem is in your "Printer Class". With a Local Printer in the printPDF Method it works. Try it:
void webview::printPDF(bool ok)
{
QPrinter printer(QPrinter::HighResolution);
QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",
QString(), "*.pdf");
printer.setPageSize(QPrinter::A4);
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
page()->mainFrame()->print(&printer);
}
UPDATE: Here a small working Example:
testview.cpp
#include "testview.h"
#include <QWebFrame>
#include "webview.h"
#include <QWebPage>
#include <QGridLayout>
testview::testview(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QGridLayout* Layout = new QGridLayout(this);
webview* w = new webview(this);
w->setMinimumSize(500, 500);
centralWidget()->setLayout(Layout);
bool a = connect(w->page()->mainFrame(), SIGNAL(loadFinished(bool)), w, SLOT(printPDF(bool)));
w->page()->mainFrame()->load(QUrl("http://stackoverflow.com"));
}
testview::~testview()
{
}
webview.cpp
#include "webview.h"
#include <QPrinter>
#include <QWebFrame>
#include <QFileDialog>
webview::webview(QWidget *parent)
: QWebView(parent)
{
}
webview::~webview()
{
}
void webview::printPDF(bool ok)
{
QPrinter printer(QPrinter::HighResolution);
QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",
QString(), "*.pdf");
printer.setPageSize(QPrinter::A4);
printer.setOrientation(QPrinter::Portrait);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
page()->mainFrame()->print(&printer);
}
The problem was elsewhere :
In my main.cpp I had this :
QObject::connect(nav->getFrame(), SIGNAL(loadFinished(bool)), nav, SLOT(printPDF(bool)));
[...]
delete args;
delete pdf;
delete nav;
return app.exec();
app.exec() is a kind of infinit loop who thaht handles Qt events and thus allows the program does not close.
If I proceed to delete before calling this function,then I will have freshly deallocated pointers that will be used
If I Do :
bool result = app.exec();
delete args;
delete pdf;
delete nav;
return result;
It's work fine !