Posts Tagged ‘simple example’

How to create a custom model for a QListView in Qt 4

Tuesday, August 2nd, 2011

Qt 4 provides a powerful model / view pattern to display custom data in various views – QListView, QTableView, etc. The problem is that the documentation for model/view programming is massive and it’s difficult to find simple examples on how to create custom models, custom views, etc.

So below is a simple example on how to create a custom model for a QListView. The model takes a std::vector of custom objects, and provides all the necessary methods. I’ve only included the minimal code so that you can get something working quickly, but of course the model can be further customized (see QAbstractListModel reference for instance).

EmployeeListModel.h

class EmployeeListModel : public QAbstractListModel {
	
	Q_OBJECT

public:

	explicit EmployeeListModel(const std::vector<Employee*>& employees, QObject* parent = 0);
	int rowCount(const QModelIndex &parent = QModelIndex()) const;
	QVariant data(const QModelIndex &index, int role) const;
	
private:
	
	std::vector<Employee*> employees_;
	
};

EmployeeListModel.cpp

#include "EmployeeListModel.h"

EmployeeListModel::EmployeeListModel(const std::vector<Employee*>& employees, QObject *parent) : QAbstractListModel(parent) {
	employees_ = employees;
}

int EmployeeListModel::rowCount(const QModelIndex& parent) const {
	return employees_.size();
}

QVariant EmployeeListModel::data(const QModelIndex& index, int role) const {
	// Check that the index is valid and within the correct range first:
	if (!index.isValid()) return QVariant();
	if (index.row() >= decks_.size()) return QVariant();
	
	if (role == Qt::DisplayRole) {
		// Only returns something for the roles you support (DisplayRole is a minimum)
		// Here we assume that the "Employee" class has a "lastName" method but of course any string can be returned
		return QVariant(employees_.at(index.row())->lastName());
	} else {
		return QVariant();	
	}
}

Usage:

EmployeeListModel* model = new EmployeeListModel(employees);
ui->employeeListView->setModel(model);

Setting up and using the Auth module in Kohana 3.1

Saturday, April 16th, 2011

The documentation about the Auth module in Kohana 3.1 is severely lacking, and the module has changed sufficiently that existing tutorials and documentations are no longer relevant.

So below is a quick tutorial on how to setup and use the module:

1) Enable the modules

If not done already, enable the needed modules in bootstrap.php. In particular, auth, database and ORM need to be enabled:

<?php
Kohana::modules(array(
    'auth'       => MODPATH.'auth',       // Basic authentication
    // 'cache'      => MODPATH.'cache',      // Caching with multiple backends
    // 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
    'database'   => MODPATH.'database',   // Database access
    // 'image'      => MODPATH.'image',      // Image manipulation
    'orm'        => MODPATH.'orm',        // Object Relationship Mapping
    // 'unittest'   => MODPATH.'unittest',   // Unit testing
    // 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
    ));
?>

2) Setup the database

– Copy the configuration file from modules/database/config/database.php to application/config/database.php
– Open it and set username, password, etc.
– Create the database schema using the SQL file in modules/orm/auth-schema-mysql.sql

You should now have a working database with all the required tables.

3) Setup the Auth module

– Copy the Auth config file from modules\auth\config\auth.php to your config folder in application/config.
– Open this file and change the driver to “ORM” and set a hash key. It can be any random value such as those generated by WordPress.
– Your file should then look like this:

<?php defined('SYSPATH') or die('No direct access allowed.');

return array(

    'driver'       => 'ORM',
    'hash_method'  => 'sha256',
    'hash_key'     => "4b 8?((~FKnpD))>8kb!B |#-uXIO24G3rc:&MG+FR{x;r#Uq4k{Ef@F4E9^-qS!",
    'lifetime'     => 1209600,
    'session_key'  => 'auth_user',

    // Username/password combinations for the Auth File driver
    'users' => array(
        // 'admin' => 'b3154acf3a344170077d11bdb5fff31532f679a1919e716a02',
    ),

);

In order for the Auth module to work, you must also set the cookie salt variable. So add this at the end of your bootstrap.php file:

Cookie::$salt = 'somerandomstring';

4) How to register a user

Once the database and Auth are setup, it is relatively easy to add a user to the database, although there are some pitfalls (see comments below). Here is the minimum code required to add a user:

<?php
$client = ORM::factory('user');
$client->email = "my@email.com";

/* Note that the username cannot contain
   certain characters such as"." or "@".
   If it does "$client->save()" is going
   to crash, and the error message is not
   helpful */
$client->username = "laurent";

/* Auth is going to automatically hash
   the password when saving the user,
   so don't do it manually */
$client->password = "mypa55word";

$client->save();
?>

After saving the user, assign a role to him (see this post comments).

5) Example login

Once this is all done, login a user is straightforwards:

<?php
$r = Auth::instance()->login("laurent", "mypa55word");
?>

You can also check if a user is currently logged in and, if so, retrieve it from the database:

<?php
$loggedIn = Auth::instance()->logged_in();
if ($loggedIn) {
    $user = Auth::instance()->get_user();
} else {
    echo "User is not logged in";
}
?>

For more information, have a look at the Auth Module API documentation.

Delete a file to the recycle bin from C++

Friday, November 14th, 2008

Today, I was looking for a way to delete a file to the recycle bin using C++, but couldn’t find any simple example, so here it is:

SHFILEOPSTRUCT operation;
operation.wFunc = FO_DELETE;
operation.pFrom = "c:\\file\to\delete.txt";
operation.fFlags = FOF_ALLOWUNDO;

SHFileOperation(&operation);

Get the 48×48 or 256×256 icon of a file on Windows

Thursday, November 13th, 2008

Getting the 16×16 and 32×32 icons on Windows is relatively easy and is often as simple as one call to ExtractIconEx.

However, getting the extra large (48×48) and jumbo (256×256) icons introduced respectively by XP and Vista is slighly more complex. This is normally done by:

  1. Getting the file information, in particular the icon index, for the given file using SHGetFileInfo
  2. Retrieving the system image list where all the icons are stored
  3. Casting the image list to an IImageList interface and getting the icon from there

Below is the code I’m using in Appetizer to retrieve the extra large icon. If needed it can easily be adapted to get the jumbo icon.

Update: To do the same thing in C#, see the link in the comments below.

#include <shlobj.h>
#include <shlguid.h>
#include <shellapi.h>
#include <commctrl.h>
#include <commoncontrols.h>

// Get the icon index using SHGetFileInfo
SHFILEINFOW sfi = {0};
SHGetFileInfo(filePath, -1, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX);

// Retrieve the system image list.
// To get the 48x48 icons, use SHIL_EXTRALARGE
// To get the 256x256 icons (Vista only), use SHIL_JUMBO
HIMAGELIST* imageList;
HRESULT hResult = SHGetImageList(SHIL_EXTRALARGE, IID_IImageList, (void**)&imageList);

if (hResult == S_OK) {
  // Get the icon we need from the list. Note that the HIMAGELIST we retrieved
  // earlier needs to be casted to the IImageList interface before use.
  HICON hIcon;
  hResult = ((IImageList*)imageList)->GetIcon(sfi.iIcon, ILD_TRANSPARENT, &hIcon);

  if (hResult == S_OK) {
    // Do something with the icon here.
    // For example, in wxWidgets:
    wxIcon* icon = new wxIcon();
    icon->SetHICON((WXHICON)hIcon);
    icon->SetSize(48, 48);
  }
}
Copyright © Pogopixels Ltd, 2008-2018