I
I
Issue2022-04-17 13:29:15
Qt
Issue, 2022-04-17 13:29:15

How to make variable available from another Qt C++ file?

Created a project through Qt Creator. It worked great, with static data. But I need the data to be taken from the passed arguments.
There is a main.cpp file:

#include "mainwindow.h"
#include <iostream>
#include <QApplication>

int main(int argc, char *argv[])
{
  if (argc == 3) {
      const char *title = argv[1];
      const char *url = argv[2];
      QApplication a(argc, argv);
      MainWindow w;
      w.setWindowTitle(title);
      w.show();
      return a.exec();
  } else {
    std::cout << "No ARGS" << std::endl;
    return 0;
  }
}

In it, the title constant works great. I add the url constant - the compiler complains that it is not used anywhere: unused variable 'url' [-Wunused-variable] .

There is a second file where I am trying this url , mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->webView->load(QUrl(url)); //"https://ya.ru"
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(ui->webView, &QWebView::linkClicked, this, &MainWindow::slotLinkClicked);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::slotLinkClicked(QUrl url)
{
    ui->webView->load(url);
}

At this end of the program it says: 'url' was not declared in this scope
When I remove the declaration of the uri constant from main.cpp and its use from mainwindow.cpp and put just a line with the address - everything works.

How can I pass an argument? there is no argv[2] variable in mainwindow.cpp.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Issue, 2022-04-17
@paulenot

Instead of the argv[2] argument, you can use QCoreApplication::arguments().at(2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question