Skip to content

Instantly share code, notes, and snippets.

@surinkim
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save surinkim/7d01fe3260ae221dc887 to your computer and use it in GitHub Desktop.
Save surinkim/7d01fe3260ae221dc887 to your computer and use it in GitHub Desktop.
A simple template class which implements snap-to-edge functionality for some QWidgets.
#include <QWidget>
const int ENABLE_STICK_VALUE = 50;
template< typename T>
class CSnapDialog
{
public:
CSnapDialog( T* source )
: m_source( source ){};
bool SnapToParent()
{
Q_ASSERT( m_source && m_source->parent() );
if ( m_source == nullptr || m_source->parent() == nullptr )
return false;
QRect rtParent = dynamic_cast<QWidget*>( m_source->parent())->frameGeometry();
QRect rtChild = m_source->frameGeometry();
QRect rtAdjust = rtParent.adjusted( - ENABLE_STICK_VALUE, - ENABLE_STICK_VALUE, ENABLE_STICK_VALUE, ENABLE_STICK_VALUE );
if( rtAdjust.contains( rtChild.topLeft() ) )
{
if ( rtChild.left() > rtParent.right() )
m_source->move( rtParent.right(), rtParent.top() );
}
else if ( rtAdjust.contains( rtChild.topRight() ) )
{
if ( rtChild.right() < rtParent.left() )
m_source->move( rtParent.left() - rtChild.width(), rtParent.top() );
}
return true;
}
private:
T* m_source;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment