对于QFileDialog,是否可以选择文件或目录,在同一UI上给用户选择(就像用户在过滤器中选择不同的文件类型并相应地更新文件列表的那样)?
答案 0 :(得分: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()
答案 1 :(得分: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);
}
}
}