1)I want to get the name of the folder for a folder monitoring Application..
Is there a way that i can filter out specific folders from being displayed using QFileDialog (For example i don't want the my documents to be displayed in the file dialog)..
2)I don't want the user to select a drive. By default in this code drives can also be selected..
dirname=QtGui.QFileDialog.getExistingDirectory(self,'Open Directory','c:\\',QtGui.QFileDialog.ShowDirsOnly)
print(dirname)
Is there a way that i can gray out the drives or some specific folders so that it can't be selected or can i set the filters for folder to prevent showing it up..
You can try setting a proxy model for your file dialog: QFileDialog::setProxyModel. In the proxy model class override the filterAcceptsRow method and return false for folders which you don't want to be shown. Below is an example of how proxy model can look like; it'c c++, let me know if there are any problems converting this code to python. This model is supposed to filter out files and show only folders:
class FileFilterProxyModel : public QSortFilterProxyModel
{
protected:
virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
};
bool FileFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel());
if (fileModel!=NULL && fileModel->isDir(index0))
{
qDebug() << fileModel->fileName(index0);
return true;
}
else
return false;
// uncomment to execute default implementation
//return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}
here's how I was calling it
QFileDialog dialog;
FileFilterProxyModel* proxyModel = new FileFilterProxyModel;
dialog.setProxyModel(proxyModel);
dialog.setOption(QFileDialog::DontUseNativeDialog);
dialog.exec();
Note that the proxy model is supported by non-native file dialogs only.
You can try using QDir.Dirs filter.
dialog = QtGui.QFileDialog(parentWidget)
dialog.setFilter(QDir.Dirs)
serge_gubenko gave you the right answer. You only had to check the folder names and return "false" for the ones which should not be displayed. For instance, to filter out any folders named "private" you'd write:
bool FileFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel());
if (fileModel!=NULL && fileModel->isDir(index0))
{
qDebug() << fileModel->fileName(index0);
if (QString::compare(fileModel->fileName(index0), tr("private")) == 0)
return false;
return true;
}
else
return false;
// uncomment to execute default implementation
//return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}
I already tested this and it works perfectly.
serge_gubenko should receive all due credit.
I know this is not exactly what you were asking, but if you're working with a QFileSystemModel, you can do it with the Name Filters option.
model = QFileSystemModel()
model.setNameFilters(["[abcdefghijklmnopqrstuvwxyz1234567890]*"])
model.setNameFilterDisables(False)
It worked for me, and I couldn't find the answer anywhere else on the internet, so I figured I post it here.
(I know my regex is trash, but using [\\w\\d]* didn't work and I was feeling lazy.)
Related
So I have a QTreeView widget that has a custom QSortFilterProxyModel as a source model, which itself wraps a custom QAbstractItemModel called: sourceModel.
My tree displays files and folders. If a file removal leaves a folder empty, the folder is automatically deleted. The implementation is below:
bool sourceModel::removeRows(int row, int count, const QModelIndex& parent)
{
if (parent.isValid())
{
auto parent_node = static_cast<Node*>(parent.internalPointer());
if (!parent.data(rootNode).toBool())
{
beginRemoveRows(parent, row, row + count - 1);
for (int i = 0; i < count; ++i)
parent_node->removeChild(row + i);
endRemoveRows();
if (parent_node->isType<Folder>() && parent_node->children() == 0)
{
removeRows(parent_node->row(), 1, parent.parent());
}
return true;
}
}
}
This works fine when removeRows is called via the proxy model, but in another instance when sourceModel calls removeRows directly, I get:
QSortFilterProxyModel: inconsistent changes reported by source model
It's as if the QSortFilterProxyModel isn't receiving or handling beginRemoveRows/endRemoveRows properly.
I've resolved this, the fix had nothing to do with the models themselves and the code posted works fine. I was calling a method directly from a context menu workflow and this was causing some sort of race condition between the proxy model and a selection model.
I have created a mixin-like proxy model (Qt5) which just adds an extra first column to another proxy model, for adding a QToolBar of actions to each row of the table view (for example, a "delete" button). The model just provides a way of populating a QList<QVariant> for the first column. The delegate must know what is the meaning of each QVariant (usually ints/enums identifying actions), and populate the QToolBar accordingly. As last feature, if there's no actions, no extra column is added (it behaves like a QIdentityProxyModel in that case). Once added, actions cannot be removed. That's a feature for another day.
The problem of today is that, when I insert actions (which I do before setting the model to the view), the cells are all blanks. So, I'm doing something wrong with the signals or who knows with what (I think the mistake is in the add_action function, at the end of the snippet):
template<class proxy_model>
class action_model : public proxy_model
{
QList<QVariant> l_actions;
public:
using base_t = proxy_model;
using base_t::base_t; // Inheriting constructors.
QModelIndex mapFromSource(const QModelIndex& source_idx) const override
{
if (!l_actions.empty() and source_idx.isValid())
return this->createIndex(source_idx.row(),
source_idx.column() + 1);
else // identity proxy case
return base_t::mapFromSource(source_idx);
} // same for mapToSource but with - 1 instead of + 1.
int columnCount(const QModelIndex& parent = QModelIndex()) const override
{ return this->base_t::columnCount() + !l_actions.empty(); }
QVariant headerData(int section, Qt::Orientation orientation, int role) const override
{
if (!l_actions.empty()) {
if (orientation == Qt::Horizontal and section == 0
and role == Qt::DisplayRole)
return "Actions"; // Testing.
else
return base_t::headerData(section - 1, orientation, role);
} else // identity proxy case
return base_t::headerData(section, orientation, role);
}
QVariant data(const QModelIndex& idx, int role) const override
{
if (!l_actions.empty()) {
if (idx.column() == 0 and role = Qt::DisplayRole)
return l_actions; // All the actions for drawing.
else
return QVariant();
} else // identity proxy case
return base_t::data(idx, role);
}
Qt::ItemFlags flags(QModelIndex const& idx) const
{
if (!l_actions.empty() and idx.column() == 0)
return Qt::NoItemFlags; // No editable or selectable
else
return base_t::flags(idx);
}
// And here, I think, is where the fun starts:
// The action could be added before or after the sourceModel
// is set or this model is connected to a view, but I don't
// how that cases are supposed to be managed.
void add_action(QVariant const& action)
{
bool was_empty = l_actions.empty();
l_actions << action;
if (was_empty and !this->insertColumns(0, 1))
throw std::logic_error("Something went wrong");
Q_EMIT this->dataChanged
(this->createIndex(0, 0),
this->createIndex(this->rowCount(), 0),
{ Qt::DisplayRole });
}
};
Without setting actions, the model works fine, both with QAbstractIdentityProxyModel and QSortFilterProxyModel as proxy_model. But, when setting actions, the view shows every cell blank, both with QSortFilterProxyModel and QAbstractIdentityProxyModel.
Here is a user-land code:
enum sql_action { DELETE };
auto* table_model = /* My QSqlTableModel */;
auto* view_model = new action_model<QIdentityProxyModel>(my_parent);
auto* table_view = new QTableView;
view_model->add_action(static_cast<int>(sql_action::DELETE));
view_model->setSourceModel(table_model);
table_view->setModel(view_model);
table_view->setSortingEnabled(true);
table_view->setAlternatingRowColors(true);
// The last column is printed in white, not with alternate colors.
table_view->show();
table_model->select();
The delegates are not a problem because I have set no one. I expect a first column with white cells, but I get an entirely white table. The column names are shown fine, except the last one, which prints just 0 as column name.
What am I doing wrong?
The problem is in your data() method.
You do not compare role to Qt::DisplayRole you assign to role
If you have actions, you either return the action entry or QVariant(), never any data
I am trying to populate a QListWidget (in icon view) with a QFileSystemModel. I want to list folders and only files with specific extension. I want to show the preview of my files as their thumbnail, so I am subclassing QIconProvider class and I am setting this to my model.
Before setting my QIconProvider to the model I have already filtered the files that I want on my model, icon(const QFileInfo & info) is called for every file that exists in the listed directory.
I have found a work around checking the extension of the file before returning my custom icon, but I am wondering if thre is a way to avoid this.
m_itemsModel = new QFileSystemModel(this);
m_itemsModel->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
m_itemsModel->setRootPath(QDir::homePath());
QStringList filters = formatsList();
m_itemsModel->setNameFilters(filters);
m_itemsModel->setNameFilterDisables(false);
ui.listView->setModel(m_itemsModel);
m_itemsModel->setIconProvider(new ThumbnailIconProvider(QRect(0, 0, 50, 50)));
my QIconProvider:
ThumbnailIconProvider::ThumbnailIconProvider(const QRect &rect)
: QFileIconProvider() {
m_rect = rect;
}
QIcon ThumbnailIconProvider::icon(const QFileInfo & info) const {
static QStringList filters = formatsList();
QString fileName = info.fileName();
QString extension = "*" + fileName.right(fileName.length() - fileName.lastIndexOf("."));
if (info.isFile() && filters.contains(extension)) {
QString path = info.absoluteFilePath();
FileDetails details = fileDetailsFromPathForRect(path, m_rect);
QPixmap pixmap = QPixmap::fromImage(details.image);
QIcon icon(pixmap);
return icon;
}
else
return QFileIconProvider::icon(info);
}
Any ideas please?
Working with a QTableView and QAbstractTableModel - when the model emits a dataChanged event for the cell being edited, the string the user has typed in the cell (but not pressed enter to 'commit' the edit) is erased.
Example: Click a cell, type '123', cell is still in edit mode waiting for more text, dataChanged is emitted and the '123' is erased, leaving an empty cell in edit mode.
Does anyone know how to stop this behaviour, or how the model can detect when the cell is being edited to prevent dataChanged events being raised for that cell?
I had the same problem. The thing is, that data() function is called with different role parameter. For displaying role==Qt::DisplayRoleand while editing it is called with role==Qt::EditRole. For example try changing
QVariant MyModel::data(const QModelIndex & index, int role) const
{
if (role == Qt::DisplayRole)
return QString("Text to Edit");
}
to
QVariant MyModel::data(const QModelIndex & index, int role) const
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return QString("Text to Edit");
}
that should do the trick
I had the same problem and found an approach without writing my own Delegate:
The problem is exactly how you described it: The data gets updated in the Background and everything you Edit gets cleared out because the dataChanged Event updates all values thus calling the data function, which returns an empty QVariant() Object if nothing is specified for the Qt::EditRole. Even Leonid's answer would always overwrite your edits with the same QString("Text to Edit").
So what I did was this:
Introduce a member variable and dafine it mutable so it can be changed by the const data function:
mutable bool m_updateData = true;
In your background data updating function, check for m_update date before emmitting the dataChanged Signal:
if (m_updateData)
emit(dataChanged(index, index));
In your data function, check for the edit role and set m_updateData to false:
if (role == Qt::EditRole)
{
m_updateData = false;
}
After the Edit is finished, the setData function is called, where you update the data in your model. Reset m_updateDate to true after you have done that.
This works perfectly for me :)
Check your model class, you should override the setData method in your model. If every thing is correct it will update model after editing data... please let me know if you have another implementation
bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid() && role == Qt::EditRole) {
int row = index.row();
int col = index.column();
//// change data
emit(dataChanged(index, index));
return true;
}
return false;
}
I think that you should use dataChanged event only for indexes that are not being edited or only for Qt::ItemDataRole::DisplayRole.
E.g. to update only second column for every row use:
emit dataChanged(index(0, 1),
index(rowCount() - 1, 1),
QVector<int>{ Qt::ItemDataRole::DisplayRole });
I have this class:
class JavaScript : public QObject {
Q_OBJECT
public:
JavaScript();
bool executeFromFile(QString file);
bool enabled;
public slots:
void setEnabled( bool enabled );
bool isEnabled() const;
private:
QScriptEngine engine;
};
The methods are defined like this:
#include "javascript.h"
JavaScript::JavaScript() {
executeFromFile("test.js");
}
bool JavaScript::executeFromFile(QString file) {
QFile scriptFile(file);
if (!scriptFile.open(QIODevice::ReadOnly)) return false;
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
engine.evaluate(contents, file);
return true;
}
void JavaScript::setEnabled( bool enabled ) {
JavaScript::enabled = enabled;
}
bool JavaScript::isEnabled() const {
return enabled;
}
I’m trying to access the public slots previously defined in the header file like the documentation says:
http://doc.qt.digia.com/qt/scripting.html#making-a-c-object-available-to-scripts-written-in-qtscript
The test.js file looks like this, just like the examples of the docs:
var obj = new JavaScript();
obj.setEnabled( true );
print( "obj is enabled: " + obj.isEnabled() );
But i’m not getting anything. It seems it doesn’t find the JavaScript object. What am I missing?
Doing a simple
print(1+1)
works just fine.
EDIT: An example in the qt4 webpage implements Q_PROPERTY. I tried this, but got the same result:
Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled)
EDIT 1: Tried implementing the initializer like this:
// javascript.h:
JavaScript(QObject *parent = 0);
// javascript.cpp:
JavaScript::JavaScript(QObject *parent) : QObject(parent) {}
Still nothing...
EDIT 2: Some examples inherits from QScriptable too:
class JavaScript : public QObject, public QScriptable {}
But that makes no difference either.
You need to create QScriptClass instead of QObject. Qt contains example of how to extend script capabilites in Qt. Take a look on Custom Script Class Example
What I think you are actually missing is adding it to the script engine.
At some point you will have to declare a script engine
QScriptEngine * engine = new QScriptEngine(this);
Then you are going to want to add your object to the engine
JavaScript* js= new JavaScript();
QScriptValue jsobj = engine->newQObject(js);
engine->globalObject().setProperty("JavaScript", jsobj );
I'm by no means an expert but I think there is something else you need to do to say
var obj = new JavaScript();
at that point you probably need to take Kamil's advice and make JavaScript a subclass of QScriptClass