But when I want to put this piece of code out of main into a function (in order to shorten the code and perform swap on elements by just giving pointers to them) QTimer refuses to work(says it's active but timeout is not triggered):

which is an object on the stack, and therefore local to the function and is deleted the moment the function finishes. Qt disconnects a connection if one of the objects (sender, receiver) is deleted, so the moment the timer finishes there is nothing connected to its timeout() signal.