Author Archives: TheMachine

About TheMachine

Software Engineer (I like thinking) and programmer. I also dabble in math, but computers are my main hobby as of late.

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();
    p_Clipboard->setText(textForClipboard);

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

Get some color back in Visual Studio 2012 icons!

If you are still using Visual Studio 2010 (or older?), then you can just ignore this. Apparently, Microsoft’s UI design team decided to change the icons to a more “monochrome” color palette in VS 2012, so what you get is essentially gray icons for everything. These icons are a far cry from what we have come to know as save, open file, open folder, etc. However, I personally don’t really care to be honest, unlike most developers. If you seriously use Visual Studio 2012, then there is no reason you shouldn’t do these two things:

  • Learn those shortcuts! This is a must. Visual Studio has so many shortcuts that most actions take two keys plus a modifier! It sure beats having to look through context menus that are so big, they fill up more than 1,080 pixels vertically…
  • Customize the layout where everything is somewhere you can find immediately. Re-arrange the toolbars and memorize the icons’ respective locations. Even if you know all the shortcuts (unlikely), there are still some things I prefer doing with the mouse–namely opening files, as it’s easier to use the mouse to browse through the files.

If this still isn’t enough, there is always the NiceVS Visual Studio extension, which appears to bring back the colored icons so many people have come to miss so much. Use at your own risk, however, as I didn’t even bother to test this plugin. If Microsoft’s made a UI decision that coincides with the Metro UI (which everyone also seems to hate), it isn’t going away easily. There’s no sense in installing a plugin to try and undo what Microsoft has done, in my opinion.

Qt Creator 2.8.0 is finally here!

At long last, we have the release version of Qt Creator 2.8.0! I can’t wait to fill up all my monitors with multiple Qt Creator windows, and refactor C++ like C# (okay, maybe not that good… yet). If I’d have to ask for a feature improvement though, it’d be speeding up the autocompletion. Visual Studio is still way ahead in terms of that, however, Qt Creator is free and open-source, so I am not complaining. 😉

You can read the Digia write-up over on their Qt blog for all the finer details.

MultiEditing Visual Studio Extension

Lately, I’ve been using Sublime Text for some lighter jobs where Visual Studio/Qt Creator just isn’t needed. I have really been loving Sublime Text’s multi-cursor feature. I can’t believe every IDE doesn’t have this! The feature is really, really handy for a lot of cases. However, I stumbled upon this handy Visual Studio plugin that emulates multiple cursors where Visual Studio does not!

It’s free, so I encourage you to pick it up today. I didn’t notice any slowdown from using the plugin, but that’s going to be minute if you have a machine capable of running Visual Studio 2012 with a whole bunch of other extensions + a giant solution (that you have been meaning to organize…). The only thing I could complain about–if I’m allowed to complain since it’s free and I love it so much–would be that some shortcuts that I use in the text editor don’t seem to work across multiple cursors. For me, this is namely the CTRL and SHIFT keys for movement and selection.

You can find the extension on the Visual Studio Extension Gallery website here. The extension worked in C# and C++, and it appears to support other languages as well.

Let me know if there are any other great VS extensions I should check out sometime! I’d also like to hear if you think Visual Studio should include this feature in an upcoming release, because I sure think it would add a great productivity enhancement for editing code.

 

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);
    aboutDialog->setFixedSize(aboutDialog->size());
    aboutDialog->open();

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: Limit Character Count in a QTextEdit

I can think of many instances of where you would want to limit the character count of a text edit. Just recently I used it to keep people from overfilling a field for a database (very important!), but there are several other, practical ways to use this. The code:

    // If the length is greater than 300 characters
    if (ui->plainTextEdit->toPlainText().length() > 300)
    {
        QString text = ui->plainTextEdit->toPlainText();
        text.chop(text.length() - 300); // Cut off at 300 characters
        ui->plainTextEdit->setPlainText(text); // Reset text

        // This code just resets the cursor back to the end position
        // If you don't use this, it moves back to the beginning.
        // This is helpful for really long text edits where you might
        // lose your place.
        QTextCursor cursor = ui->plainTextEdit->textCursor();
        cursor.setPosition(ui->plainTextEdit->document()->characterCount() - 1);
        ui->plainTextEdit->setTextCursor(cursor);

        // This is your "action" to alert the user. I'd suggest something more
        // subtle though, or just not doing anything at all.
        QMessageBox::critical(this,
                              "Error",
                              "Please be sure that you keep the description under 300 characters.");
    }

The best place to put this would be in the textChanged() signal so it checks every time the user updates the text edit. You could also insert it before, say, writing the text out to a file.

Quick Tip: Customize Qt Tooltips with Style Sheets

I’ve been working on an application recently, and I was utilizing a custom version of Qt’s Fusion style. I got the theme looking really sleek, but then I noticed the ugly tooltips. :/ I knew there had to be a way to do this! I spent about 2 minutes thinking and searching the Qt Documentation before I realized that there was such a thing as style sheets in Qt! 😛

It’s one of those things that I had never really used just because I hadn’t bothered. That figures… anyway, style sheets are extremely helpful when you want to customize the look and feel of your application. In this case, we’ll change some attributes of the QToolTip.

    qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }");

This style results in a tool tip looking something like this:

Custom Tooltip

Create a custom tooltip using Qt Style Sheets

You can certain style it differently using the CSS-like properties. 😉

Quick Tip: Quickly Access All QWidgets in a GUI

The other day, I was trying to change the color palette of all widgets in a GUI application to implement a theme change. I was having problems getting all the widgets to change their palette without having to destroy and re-create the MainWindow. Instead, I found a handy way to easily iterate over all your QWidgets. Enjoy!

        QList<QWidget*> widgets = this->findChildren<QWidget*>();

        foreach (QWidget *widget, widgets)
        {
            widget->setPalette(this->darkPalette);
        }

If you look closely, all we are doing is getting a container of QWidget pointers that contains everything inside the MainWindow (this). We can use the findChildren template function to get all the children that are QWidget pointers. Then we simply use the handy foreach loop to iterate over all these very easily.

Note, you can access all QWidget methods, so this could be very useful for other things besides setting the palette. One example that comes to me off the top of my head is accepting/denying drops. Very handy indeed. 🙂

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;
                break;
            }
            else
            {
                illegalFile = false;
            }
        }

        if (illegalFile)
        {
            QDir dir;
            dir.remove(it.filePath());
            qDebug() << "Removed unsafe file.";
        }
    }
    
    return app.exec();
}