Saturday, February 16, 2013

QT Console Application Template Tutorial

Writing a command line program in QT may be a little harder than you would expect; particularly if you want to use the full features of QT including Signals, Slots and Threads.

If you start writing a QT program as a standard “main” program in “c” none of the QT messaging structure will operate as expected.

I have written many QT command line programs, some are commercial products.  Here is a template that I have developed which seems to work well.

Lets get started:

Here is the main.cpp file where it all starts.

#include <QtCore/QCoreApplication>
#include <QTimer>
#include "mainclass.h"
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);


    // create the main class
    MainClass myMain;


    // connect up the signals
    QObject::connect(&myMain, SIGNAL(finished()), 

             &app, SLOT(quit()));
    QObject::connect(&app, SIGNAL(aboutToQuit()), 

             &myMain, SLOT(aboutToQuitApp()));

    // This code will start the messaging engine in QT and in
    // 10ms it will start the execution in the MainClass.run routine;
    QTimer::singleShot(10, &myMain, SLOT(run()));
    return app.exec();
}

 

A few things worth noting here.
  • A instance of the MainClass class called myMain is created.  
  • A signal in that MainClass called "finished" actually quits the application.
  • A signal from the app works with a slot in myMain called aboutToQuitApp
  • A 10ms timer sends a signal to the slot run in the myMain class.  This bootstraps your code.
  • The last line “return app.exec()” starts all of the QT messaging including the Slots and Signals system across various threads.
  • By the time myMain gets the signal on the “run” Slot the QT application structure is up and running.

Now lets create the header file for the MainClass;  mainclass.h

#ifndef MAINCLASS_H
#define MAINCLASS_H
#include <QObject>
#include <QCoreApplication>
class MainClass : public QObject
{
    Q_OBJECT
private:
    QCoreApplication *app;


public:
    explicit MainClass(QObject *parent = 0);
    /////////////////////////////////////////////////////////////
    /// Call this to quit application
    /////////////////////////////////////////////////////////////
    void quit();


signals:
    /////////////////////////////////////////////////////////////
    /// Signal to finish, this is connected to Application Quit
    /////////////////////////////////////////////////////////////
    void finished();


public slots:
    /////////////////////////////////////////////////////////////
    /// This is the slot that gets called from main to start everything
    /// but, everthing is set up in the Constructor
    /////////////////////////////////////////////////////////////
    void run();


    /////////////////////////////////////////////////////////////
    /// slot that get signal when that application is about to quit
    /////////////////////////////////////////////////////////////
    void aboutToQuitApp();
};
#endif // MAINCLASS_H


Lets look at a couple of things here.

  • Call “quit()” when you want to exit the application
  • The “finished” signal is sent to the app to close the application
  • The “run() slot is where your code “starts” gets called 10ms after the application is started
  • “aboutToQuitApp() slot gets called after the “finished” signal is executed by the QT application.

The last thing to look at is the actual mainclass.cpp code.

#include "mainclass.h"
#include <QDebug>
MainClass::MainClass(QObject *parent) :
    QObject(parent)
{
    // get the instance of the main application
    app = QCoreApplication::instance();
    // setup everything here
    // create any global objects
    // setup debug and warning mode
}


// 10ms after the application starts this method will run
// all QT messaging is running at this point so threads, signals and slots
// will all work as expected.
void MainClass::run()
{
    // Add your main code here
    qDebug() << "MainClass.Run is executing";
    // you must call quit when complete or the program will stay in the
    // messaging loop
    quit();
}


// call this routine to quit the application
void MainClass::quit()
{
    // you can do some cleanup here
    // then do emit finished to signal CoreApplication to quit
    emit finished();
}


// shortly after quit is called the CoreApplication will signal this routine
// this is a good place to delete any objects that were created in the
// constructor and/or to stop any threads
void MainClass::aboutToQuitApp()
{
    // stop threads
    // sleep(1);   // wait for threads to stop.
    // delete any objects
}


There are a few things to discuss here:

  • The constructor gets a instance of the QT application and sets it to “app”
  • The “run” slot is where your code will actually start execution.
  • When you are through running your code you must call “quit” to stop the application.  This will tell the QT application to terminate.
  • While the QT application is in the process of terminating it will execute the slot aboutToQuitApp().  This is a good place to do any clean-up work.

Well I hope this helps you get a QT Console application up and running quickly.

Comments are welcome.

23 comments:

  1. Nice blog post Trey! I am new to QT but enjoying the framework so far. I needed an example on how to write console applications in the tool.

    ReplyDelete
  2. Hi Trey, thanks for the perfect blog post! I just wonder why do I need the pointer to QCoreApplication in the MainClass (QCoreApplication *app)? Thanks

    ReplyDelete
  3. Very nice post. Very much appreciated!
    Thank you.

    ReplyDelete
  4. The first example of a Qt console application with event loop which exits cleanly. Extremely helpful, THANK YOU!

    ReplyDelete
  5. Trey, thanks for the example. One more advanced question, since you've used console apps with Qt in products - how do you handle user input in your console app? Do you spawn a separate thread that polls stdin periodically?

    I've got a TCP/IP socket server I'd like to dump the UI from and move it to a console GUI - but I don't want to use nCurses/PDCurses - just regular ol' console.

    Thanks!

    ReplyDelete
  6. there is another way to do it from a consol application

    MyClass w;
    while (w.QStringListData.isEmpty())
    { // wait till calculation is done
    QCoreApplication::processEvents();
    }
    qWarning() << "data ready " << w.QStringListData.at(0);

    ReplyDelete
  7. Hello! I try to use your code. But program close faster then code is complete.

    void MainClass::run()
    {
    QStringList arguments;
    arguments.append("https://nomads.ncep.noaa.gov/cgibin/filter_gfs_0p25.pl");
    DownloadManager *manager = new DownloadManager;
    manager->append(arguments);
    QObject::connect(manager, &DownloadManager::finished, manager,&DownloadManager::emptySlot);

    quit();
    }

    DownloadManager from https://code.qt.io/cgit/qt/qtbase.git/tree/examples/network/downloadmanager?h=5.14

    ReplyDelete
  8. The websites we've mentioned above for freelancers such as Upwork , Fiverr and Freelancer are great places to market your services, as well as reaching out to companies directly. I have been an affiliate for few programs but failed to make a profit because I haven't done it correctly. Here are three real-life affiliate marketing success stories from people at different stages of their affiliate marketing careers. While an affiliate business doesn't require substantial financial investment, you are going to be investing a valuable resource; your time. One extra benefit is that when you link to a product with your Amazon affiliate link, you get credit for any product the user purchases in that session. They're long links, that often go to a secondary domain, and are pretty clear that they're an affiliate.

    Moreover, even if a random user who once checked your product through one of your affiliate marketing program leaves without making any purchase, there is a high chance that the same user will return someday to buy something. While content marketing isn't an overnight success like PPC might be, no other tactic can match its long-term viability. There are services that will do all the marketing for you for a fee, but to start out, you can do the marketing yourself. You will commonly see lifestyle, fashion, and beauty influencers using these affiliate programs because it makes affiliate marketing multiple items really easy. We also read that affiliate marketing has continued to grow, and the most recent figures on the industry from research conducted by the IAB concluded that $16.5 billion worth of sales was driven by the affiliate channel, while advertisers spent $1.1 billion on affiliate marketing in 2014, 8% more than in 2013. https://www.reviewengin.com/simple-tips-to-starting-an-affiliate-marketing-online-business/

    ReplyDelete
  9. The combination of paid search and content advertising provides you a cohesive web marketing whole. When you finally start creating content, you have to know who you’re speaking to and tailor your model voice to enchantment to them uniquely. If you aren’t targeting the best viewers (these people who will lean in to hear what you’re saying), you won’t discover success. And, when you can’t find a method to stand out, you’ll mix into the hordes of other brands competing for consideration in your industry. Multicultural advertising is devising and executing a marketing marketing campaign that targets folks of different ethnicities and cultures inside a model’s overarching viewers. https://www.reviewengin.com/6-tips-on-strategic-instagram-marketing/

    ReplyDelete
  10. It is the reason why an American consumer can pick between a Japanese, German, or American car. As a result of international trade, the market contains greater competition and therefore, more competitive prices, which brings a cheaper product home to the consumer. Today, trade is merely a subset within a complex system of companies which try to maximize their profits by offering products and services to the market at the lowest production cost. A system of international trade has helped to develop the world economy but, in combination with bilateral or multilateral agreements to lower tariffs or to achieve free trade, has sometimes harmed third-world markets for local products. In theory, economies can, therefore, grow more efficiently and can more easily become competitive economic participants. For the receiving government, FDI is a means by which foreign currency and expertise can enter the country.

    to exchange a less valuable or desirable item for a more valuable or desirable one. to exchange a more valuable or desirable item for a less valuable or desirable one.

    Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Such ideas have also sparked a debate on whether trade itself should be codified as a human right. Protectionism is the policy of restraining and discouraging trade between states and contrasts with the policy of free trade. Protectionist policies were particularly prevalent in the 1930s, between the Great Depression and the onset of World War II. January 1, 1995 World Trade Organization was created to facilitate free trade, by mandating mutual most favored nation trading status between all signatories. The Great Depression was a major economic recession that ran from 1929 to the late 1930s.

    From our signature policymaking event, Organic Week in Washington, D.C., to a full roster of education and networking events at the Natural Products Expos, join us for association business, member meetings, and social and networking events. Screen for heightened risk individual and entities globally to help uncover hidden risks in business relationships and human networks. Access to real-time, reference, and non-real time data in the cloud to power your enterprise. "This new national flagship will be the first vessel of its kind in the world, reflecting the UK's burgeoning status as a great, independent maritime trading nation," Prime Minister Boris Johnson said. You are solely responsible for removing all data, including confidential and personal data, from the device prior to shipping. https://www.reviewengin.com/trade-command-center-review/

    ReplyDelete
  11. The Forex market is filled with hundreds of different trading strategies, but what are the best Forex trading strategies for beginners? This is a common question among traders just starting out and for good reason. AxiTrader Limited is amember of The Financial Commission, an international organization engaged in theresolution of disputes within the financial services industry in the Forex market. One good rule of thumb, especially for new traders, is to never risk more than 1% of your trading capital while in learning mode.Make sure to talk to your broker about implementing a stop-loss in your portfolio, in order to automatically close out of trading if you ever reach a predetermined amount of losses. You can also put a stop-limit on a single currency you’re holding, preemptively telling your trader to sell if the currency ever reaches below X price. As a general rule of thumb, do not bid with more than you can afford to pay back. Conversely, in a non-spot market, also known as futures, or a future transaction, both parties agree to buy/sell currencies at the current price, but make the actual swap down the line. Forex traders rely heavily on charts in order to make educated guesses about how a currency value will change by observing historical fluctuation patterns. Nearly all charts have personalized setting options to allow traders to view a variety of technical indicators like price, volume, etc. in order to analyze price movements.Depending on where the dealer exists, there may be some government and industry regulation, but those safeguards are inconsistent around the globe. In the forwards market, contracts are bought and sold OTC between two parties, who determine the terms of the agreement between themselves. In the futures market, futures contracts are bought and sold based upon a standard size and settlement date on public commodities markets, such as the Chicago Mercantile Exchange. A forward contract is a private agreement between two parties to buy a currency at a future date and at a predetermined price in the OTC markets. A futures contract is a standardized agreement between two parties to take delivery of a currency at a future date and at a predetermined price. Forex markets exist as spot markets as well as derivatives markets, offering forwards, futures, options, and currency swaps. https://www.reviewengin.com/trade-juice-review/

    ReplyDelete
  12. Situs Judi Slot Online Terbaik Indonesia, Judi Online
    Pragmatic Play merupakan slot yang berdiri jenis game judi slot online septcasino sudah agen slot, slot machine joker123, seperti worrione judi bola, kadangpintar judi bola online

    ReplyDelete
  13. There is no reason you shouldn’t want to join it if you are an eCommerce business geek. Kibo Code Eclipse already seems to be a hit because its previous programs have been successful. Businesses of all sizes, even those without prior experience in the business world, recognize its benefits. Applicants of the program also receive bonus items that they can access from their personalized eCommerce platform.
    If you’re interested in trying the program, you should purchase it from the official website. As a caution, this online training course hasn’t been launched yet and isn’t offered by any other forum or platform. The standard price for this Kibo Eclipse program and the bonus items is only $3,497 or four payments that total $999. It’s easy to enroll in the Kibo Eclipse course, just by using a smartphone, tablet, or computer. As a matter of fact, it’s better to use a computer or a laptop, as setting up an online business and running it does involve having a bit of technological availability.
    “Kibo Eclipse is a completely new system and a different approach. It is not a reboot system of the previous version,” said one of the founders, Aidan Booth. You will be able to access 3 types of bonuses – The core manual, the profit map, and the case studies. The fourth module gives you access to some services exclusively done for you and some products from the remote repository of the Kibo Eclipse system. It is normal to have questions regarding a new product or offer, but Kibo Eclipse has all that it takes to believe it.
    The new features will help the user in entering new marketplaces and operate successfully with ease. Someone who needs to start a business can be proud of and possibly make them rich. An existing eCommerce store owner who wants to find new ways to make money in the eCommerce industry but does not want to spend a bundle but wants proven results.
    Plus, access to tools including website making, marketing funnels, email templates, and much more are also included. But again though it’s not that cheap, yet it is the juice of efforts of two successful entrepreneurs who claim this model as truly inspiring and life-changing. And just so you know, the fulfilment process is fast and easy and you NEVER need to see or handle any of the products you’ve sold. The second step is all about aiming to reach an initial milestone of $1000/week in profit by taking advantage of instant, hypertargeted FREE traffic from the Facebook marketplace.
    Kibo Eclipse - https://www.reviewengin.com/kibo-eclipse-review/

    ReplyDelete
  14. When you understand what your website users want, you can then implement that knowledge across your campaigns , across your website, across your social media properties, and more. Also note, features like rich results and Knowledge Panels in the search results can increase visibility and provide users more information about your company directly in the results. Costs arise solely from the optimisation process where agencies are paid to improve positions in the search results. Be active on social media and link to high-quality content frequently. Thankyou for sharing such a nice article and your knowledge with us.
    Sullivan credits Bruce Clay as one of the first people to popularize the term. External optimization tactics that take place outside of your site rather than on it are referred to as off-page SEO. Backlink building is the most common off-page SEO approach since excellent backlinks from external sites inform search engines that your site is valuable and high-quality, which increases authority.
    Online competition is fiercer than ever—and if you want to create a website that outperforms industry benchmarks in a big way, it’s vital that you know how to utilize your design skills to keep users engaged. On-page SEO is the work you do on your own website to get a high rank in search engines. Your goal is obviously that your website will show on the first page and perhaps even among the first three search results. On-page SEO does not carry as much weight as off-page SEO in the rankings, but if you don’t get the basics right… it’s unlikely that your off-page SEO will deliver results, either. https://www.reviewengin.com/category/seo/

    ReplyDelete
  15. You could even use Facebook Shop features like Live Streaming to host real-time tutorials with influencers on how to use and get the most out of your products. Facebook Shops enables you to set up a store on Facebook’s platform that potential and existing customers can use to buy your products without leaving the platform. In the early days, it might have been enough for a brand to send an influencer one of their products as a gift, in return for them posting about it on their profile. But this changed with the rapid growth of the space, as influencers realised they could not only gain free products, but actually charge brands for grid real estate on their profile. Just because a marketing tactic is trending doesn’t mean that companies will succeed in their execution.
    If content does not feel native to the Facebook/Instagram ad platform and isn’t optimized for strong paid branding, Facebook will likely de-prioritize your ads in the news feed. It seems Twitter influencers do, as a matter of fact, have the ability to impact the purchasing decisions of followers. Engaging in marketing campaigns with influencers clearly has the potential to drive up sales of goods and services and newsjacking on Twitter may also be something to consider.
    The campaign also included 360-degree videos, enabling fans to experience the trip through each influencer’s eyes. Primarily, influencers act as a mutual friend connecting your brand with your target consumers. An endorsement from an influencer has the power to drive traffic to your site, amplify your message across social media platforms, and even directly sell your product through their recommendation. https://www.reviewengin.com/5-reasons-you-should-take-advantage-of-influencer-marketing/

    ReplyDelete
  16. Therefore, making money online isn’t that complicated but people fail because of the lack of consistency. The amazing thing about affiliate marketing is that you can grow your own audience to sell those products. Affiliate marketing is promoting other people’s products for a commission. Additionally, people don’t know that using Youtube as a paid traffic source has a massive opportunity to sell products. I technology to create video content, therefore you can promote products from any affiliate network to your funnel.
    They would stock vehicles with popular equipment combinations and allow deliveries in as little as four days, Reuss said. “This will again set the standard of the world for performance,” he said. The company says its modular Ultium EV architecture is flexible enough to allow multiple battery chemistries and cell sizes, and it can handle multiple vehicles. That’s one reason the company says the next two years put it on a path to double revenue by 2030. Despite economic volatility and the possibility of a downturn, GM appeared more confident in this year’s financial results, saying Thursday it expects full-year pretax income to be $13.5 billion to $14.5 billion.
    As you see, this business model has nothing to do eCommerce, Crypto or Internet Marketing niche. There is little known about the new business model from Aidan Booth and Steve Clayton that's coming out in January 2023. You don’t need to deal with suppliers, customer support, product inventory, or any of the usual headaches.
    Saudi Tadawul Group Holding Co. also fell 3.48 percent to close at SR172 per share. On the banking front, Saudi National Bank, the Kingdom’s largest lender, gained 1.3 percent, while Saudi Arabia’s most valuable bank, Al Rajhi, slipped 0.12 percent. The oil giant — known as Aramco — has earlier posted a 39 percent surge in the third quarter of 2022, surpassing the average of analysts’ forecasts. https://www.reviewengin.com/123-profit-review/

    ReplyDelete
  17. Thanks and I have a neat present: House Renovation complete house renovation

    ReplyDelete