/
recentfilemenu.cpp
106 lines (91 loc) · 2.39 KB
/
recentfilemenu.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <QSettings>
#include <QVariant>
#include <QDebug>
#include "recentfilemenu.h"
RecentFileMenu::RecentFileMenu( QString title, QWidget *parent ) :
QMenu( title, parent )
{
}
void RecentFileMenu::clear(){
foreach( QString filename, mRecentFiles )
{
removeRecentFile( filename );
}
QMenu::clear();
mRecentFiles.clear();
mRecentActions.clear();
}
void RecentFileMenu::setRecentFiles( QStringList filenames )
{
clear();
foreach( QString filename, filenames )
{
if ( filename != "" ) {
addRecentFile( filename );
}
}
}
bool RecentFileMenu::loadFromDisk()
{
QSettings settings( PENCIL2D, PENCIL2D );
QVariant _recent = settings.value( "RecentFiles" );
if ( _recent.isNull() )
{
return false;
}
QList<QString> recentFileList = _recent.toStringList();
setRecentFiles( recentFileList );
return true;
}
bool RecentFileMenu::saveToDisk()
{
QSettings settings( PENCIL2D, PENCIL2D );
settings.setValue( "RecentFiles", QVariant( mRecentFiles ) );
return true;
}
void RecentFileMenu::addRecentFile( QString filename )
{
if ( mRecentFiles.contains( filename ) )
{
removeRecentFile( filename );
}
while ( mRecentFiles.size() >= MAX_RECENT_FILES )
{
removeRecentFile( mRecentFiles.last() );
}
mRecentFiles.prepend( filename );
QAction* action = new QAction( filename, this );
action->setData( QVariant( filename ) );
QObject::connect( action, SIGNAL( triggered() ), this, SLOT( onRecentFileTriggered() ) );
mRecentActions.insert( filename, action );
if ( mRecentFiles.size() == 1 )
{
addAction( action );
}
else
{
QString firstFile = mRecentFiles[ 1 ];
qDebug() << "Recent file" << firstFile;
insertAction( mRecentActions[ firstFile ], action );
}
}
void RecentFileMenu::removeRecentFile( QString filename )
{
if ( mRecentFiles.contains( filename ) )
{
QAction *action = mRecentActions[ filename ];
removeAction( action );
mRecentActions.remove( filename );
mRecentFiles.removeOne( filename );
delete action;
}
}
void RecentFileMenu::onRecentFileTriggered()
{
QAction*action = ( QAction* )QObject::sender();
QString filePath = action->data().toString();
if ( !filePath.isEmpty() )
{
emit loadRecentFile( filePath );
}
}