Tag Archives: Programming Tutorial

The Holy Grail of Excel Macros

Okay, so, you just got handed a job for a 100+ page workbook. Your client wants you to fix some formatting or something of the like on every page (the 100 pages already exist… creating that many is a different story…). What do you do? You use macros and let the computer do all the work, silly! 😛 The best part is you can charge for all the hours it would have taken you to fix it all up without the snippet I’m about to give you! (Okay, this is probably a tad unethical…).

You’re interested? I thought so. We’re going to use the power of foreach loops to let the computer run through and do all this on every single page. The workflow I use looks something like this:

  1. On the first page (or a “test” page), I hit Record Macro and name it something I can remember. Be sure that you remember what the exact name of it is. This is very important. 
  2. Proceed to style/do whatever it is that you’re being paid to do. Ahem. 
  3. Once you’re done, stop recording the macro. At this point, I usually like to test the macro before I use it on my entire workbook, just to make sure it isn’t going to destroy it all. 😛
  4. If you have verified the integrity, now we need to write a bit of code. :O But I have never used the Visual Basic editor! Don’t worry–it’s incredibly simple and you can basically copy and paste this snippet I’m about to give you and just change one little bit for all your repeating macros. 

Let’s get on to the code now, shall we?

Continue reading


Quick Tip: Load Fonts from a Local File with QML

If you are familiar with CSS, you have probably loaded an external font before. With an Internet application, you usually wouldn’t load it from a file, but for a desktop application that doesn’t require an Internet connection, loading from a file is a must. Luckily, this is extremely easy and the TTF file can be embedded right in the executable using the Qt resource system (QRC protocol). In QML, there is a provided FontLoader element that makes quick work of loading fonts. Here’s quick example:

FontLoader { id: myCustomFont; source: "qrc:/fonts/myCustomFont.ttf" }

Note that if you want to do so, it is possible to directly link to a URL on the Internet. However, I wouldn’t recommend this unless you can ensure that your user will have an Internet connection at run-time. Otherwise, I would recommend downloading the TTF file instead and putting it in a local resource file. Be sure to read the license before doing this though!

When you want to use the font later in a font field, for example, you can simply do:

font.family: myCustomFont.name

And that’s it! You are all set to use custom Truetype Fonts in QML! I hope this helps you out with your QML application. Happy coding!

Quick Tip: Copy Any Text to the System Clipboard in Qt

Now, this is a super quick tip, as it’s really a no-brainer. The explanation (if you need one) is that a QApplication has a global instance of the clipboard, which can be accessed by simply getting a pointer to it. So lets just get to the code!

    QClipboard *p_Clipboard = QApplication::clipboard();

And viola! Just like that, your text should now be on the system clipboard. Happy coding!

Quick Tip: Qt 5 Standard Paths

In Qt 5, the way you retrieve standard paths for a system has changed. Now, you use a special class named QStandardPaths instead of the desktop services class. By far my favorite use for this is locating directories without user interaction. In this quick example, we’ll locate the user’s home directory. Note that you can use any of the provided enums in replace of QStandardPaths::HomeLocation.

QString homeLocation = QStandardPaths::locate(QStandardPaths::HomeLocation, QString(), QStandardPaths::LocateDirectory);

This will return C:/Users/Admin on my development PC. This should work cross platform as well, so no more fiddling with the preprocessor to decide which default location to use. 🙂 You can replace the QString() with additional details for location.

Quick Tip: Using Multiple UI Files in a Qt Application

This is way easier than I first realized with Qt. If you are having troubles figuring this out, do not look any further! Now, it seems I make a habit of trying to figure out how to do things in Qt without consulting my C++ 101 chapters in all those books I read a long time ago. 😛 Every form is a class, (e.g. mainwindow.h/mainwindow.cpp), and if you look in your main function… what does it do? Of course! It just creates an instance and shows it! That easy! Now, there are a few things you can do, but this is the gist of it:

    AboutDialog *aboutDialog = new AboutDialog(this);
    aboutDialog->setAttribute(Qt::WA_DeleteOnClose, true);

Now, this is just some code that I generally use to show a custom about dialog. The main parts you should note are line 1 and 4. On line 1, we instantiate a pointer to an AboutDialog (be sure to include the header file). We use a pointer because, well, if you try using a scoped object, it usually [always] doesn’t work. The dialog simply will disappear because the object is destroyed when it goes out of scope. (Note: this works in main because you have the event loop, i.e. app.exec()).

The middle 2 lines are simply “parameters” I’ve set for this particular dialog. The 2nd line just makes it so the pointer is deleted on closing the dialog. You might not want this if you are using a dialog with data you store in its members. That’s common of a non-modal dialog in my experience. The 3rd line sets the fixed size. This is actually one way to do this, and you can find a plethora of other ways to set a fixed size for your dialog.

The 4th line is rather interesting, as you can change how a window is opened by using either open() or show(). They both yield different results. Basically, open() is just going to open the dialog as a modal dialog, whereas show() is more appropriate for something that’s going to have a longer life-span in the application. I encourage you to play around with this, as it will truly add another layer of depth if you are trying to cram everything into one form! 😉

Quick Tip: Delete Certain Files from a Directory in Qt

I’ve been working on application lately that needs to recursively scan through directories and delete files that could potentially cause harm to someone’s computer. I won’t go into the specifics now, as this is a quick tip, but let me go over the algorithm really quick before we get to the code.

Basically, we use a QDirIterator to scan through all directories and files. The iterator can give us useful info. Literally, you can get a QFileInfo instance for the file/dir, which can be very useful to subsidize the code if you are just looking for something like, say, executables. We also have a QStringList of all the file types you don’t want, i.e. illegalFileTypes. We iterate over these until we find a match with one of these types. If we do, a simple boolean is flagged to destroy the file and we remove it.

Now, you could easily add a simple message box or something in a GUI application to confirm the deletion, which would be more sensible if you are scanning a small tree of files. However, if you are wanting to ask confirmation from the user on something much larger (>200-300 files), I’d modify the code so that it notifies the user in another way, or perhaps moves the files silently to another directory.

And… here’s the code! This is just a slap-together. You could easily turn this into a function and add an argument for the illegal file types if you want to re-use this code.

#include <QCoreApplication>
#include <QDirIterator>
#include <QDir>
#include <QDebug>
#include <QFileInfo>
#include <QStringList>

int main(int argc, char *argv[])
    QCoreApplication app(argc, argv);

    QDirIterator it("C:/Users/Admin/Desktop/PatchIt Test Folder", QDirIterator::Subdirectories);

    QStringList illegalFileTypes;
    illegalFileTypes << ".exe" << ".dll" << ".py" << ".jar" << ".au3" << ".lua" << ".msi";

    while (it.hasNext())
        qDebug() << "Processing: " <<it.next();

        bool illegalFile;

        foreach (QString illegalType, illegalFileTypes)
            if (it.fileInfo().absoluteFilePath().endsWith(illegalType, Qt::CaseInsensitive))
                illegalFile = true;
                illegalFile = false;

        if (illegalFile)
            QDir dir;
            qDebug() << "Removed unsafe file.";
    return app.exec();

Quick Tip: Download a File in Qt

Someone asked me a while back how to simply download a file in Qt. I mean, Qt is so mature and so extensive that you think something like this would be one function call away–wrong. It actually takes a whole class to do it right! The idea is basically that you want to get a QNetworkRequest going for your URL in a reply, and from there it’s basics. I’m going to keep the explanations quick, since this is a quick tip, and just post mainly the bare-bones code for this.

Note that this is some code taken from a past QML project of mine, so note the “Handler” in the class name and the affluent use of signals/slots for everything.

Continue reading