对于 QFileDialog,是否可以选择文件或目录,在同一 UI 上为用户提供选择(例如用户在过滤器中选择不同文件类型并相应更新文件列表的方式)?
问问题
1298 次
2 回答
1
我做了一些研究,并在 IRC ppl 的帮助下找到了一个更简单的解决方案。基本上添加一个小部件(复选框,适合这个)并将其连接到文件对话框就可以了。
(这实际上是别人的答案,我已经改进和布置了。感谢他;)。如果其他人在这里绊倒,请在此处发布答案以供参考)。
from sys import argv
from PySide import QtGui, QtCore
class MyDialog(QtGui.QFileDialog):
def __init__(self, parent=None):
super (MyDialog, self).__init__()
self.init_ui()
def init_ui(self):
cb = QtGui.QCheckBox('Select directory')
cb.stateChanged.connect(self.toggle_files_folders)
self.layout().addWidget(cb)
def toggle_files_folders(self, state):
if state == QtCore.Qt.Checked:
self.setFileMode(self.Directory)
self.setOption(self.ShowDirsOnly, True)
else:
self.setFileMode(self.AnyFile)
self.setOption(self.ShowDirsOnly, False)
self.setNameFilter('All files (*)')
def main():
app = QtGui.QApplication(argv)
dialog = MyDialog()
dialog.show()
raise SystemExit(app.exec_())
if __name__ == '__main__':
main()
于 2012-11-06T14:12:44.713 回答
0
是的。这是一种方法:
在标题中,声明您的QFileDialog
指针:
class buggy : public QWidget
{
Q_OBJECT
public:
buggy(QWidget *parent = 0);
QFileDialog *d;
public slots:
void createDialog();
void changeDialog();
};
在您的实现中,设置QFileDialog::DontUseNativeDialog
选项(您必须在 Mac OS 上执行此操作,但我没有在其他地方测试过),然后覆盖适当的窗口标志以使您的对话框按您喜欢的方式显示。
最后,添加一个按钮(或复选框)调用一个函数来改变你的文件模式QFileDialog
:
buggy::buggy(QWidget *){
//Ignore this, as its just for example implementation
this->setGeometry(0,0,200,100);
QPushButton *button = new QPushButton(this);
button->setGeometry(0,0,100,50);
button->setText("Dialog");
connect( button, SIGNAL(clicked()),this,SLOT(createDialog()));
//Stop ignoring and initialize this variable
d=NULL;
}
void buggy::createDialog(void){
d = new QFileDialog(this);
d->setOption(QFileDialog::DontUseNativeDialog);
d->overrideWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint | Qt::MacWindowToolBarButtonHint);
QPushButton *b = new QPushButton(d);
connect(b,SIGNAL(clicked()),this,SLOT(changeDialog()));
b->setText("Dir Only");
switch(d->exec()){
default:
break;
}
delete(d);
d=NULL;
}
//FUNCTION:changeDialog(), called from the QFileDialog to switch the fileMode.
void buggy::changeDialog(){
if(d != NULL){
QPushButton *pb = (QPushButton*)d->childAt(5,5);
if(pb->text().contains("Dir Only")){
pb->setText("File Only");
d->setFileMode(QFileDialog::Directory);
}else{
pb->setText("Dir Only");
d->setFileMode(QFileDialog::ExistingFile);
}
}
}
于 2012-11-06T14:02:24.200 回答