Recently I've written some code which implements snap-to-edge functionality for some windows.
There is some code duplication as you can see. I think this code can be simpler or possibly improved.
// If 'rtParent' and 'rtChild' are closed each other as 'ENABLE_STICK_VALUE', return true;
auto IsNearEachOther = []( const QRect& rtParent, const QRect& rtChild ) -> std::tuple< bool, QPoint>
{
bool isNear = false;
QPoint ptMoveTarget;
// If 'rtChild's left position is closing to 'rtParent's right position.
if ( rtChild.left() > rtParent.right() )
{
if ( ( ( rtChild.left() - rtParent.right() ) <= ENABLE_STICK_VALUE )
&& ( rtChild.top() >= ( rtParent.top() - ENABLE_STICK_VALUE ) )
&& ( rtChild.top() <= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
{
isNear = true;
ptMoveTarget = QPoint( rtParent.right(), rtParent.top() );
}
}
// If 'rtChild's right position is closing to 'rtParent's left position.
if ( rtChild.right() < rtParent.left() )
{
if ( ( ( rtParent.left() - rtChild.right() ) <= ENABLE_STICK_VALUE )
&& ( rtChild.top() >= ( rtParent.top() - ENABLE_STICK_VALUE ) )
&& ( rtChild.top() <= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
{
isNear = true;
ptMoveTarget = QPoint( rtParent.left() - rtChild.width() , rtParent.top() );
}
}
return std::make_tuple( isNear, ptMoveTarget );
};
QRect rtParent = m_pParentChatRoom->geometry();
QRect rtCurrent = geometry();
bool result = false;
QPoint ptMoveTarget;
std::tie( result, ptMoveTarget ) = IsNearEachOther( rtParent, rtCurrent );
if ( result )
{
move( ptMoveTarget );
}