Beispiel #1
0
    def showFiles(self, files):
        for fn in files:
            file_ = QtCore.QFile(self.currentDir.absoluteFilePath(fn))
            size = QtCore.QFileInfo(file_).size()
            dateCreated = QDateTime.toString(QtCore.QFileInfo(file_).created())
            dateCreated_ = str(dateCreated)
            dateCreated_.encode("ascii", "ignore")

            fileNameItem = QtGui.QTableWidgetItem(fn)
            fileNameItem.setFlags(fileNameItem.flags()
                                  ^ QtCore.Qt.ItemIsEditable)
            sizeItem = QtGui.QTableWidgetItem("%d KB" % (int(
                (size + 1023) / 1024)))
            sizeItem.setTextAlignment(QtCore.Qt.AlignVCenter
                                      | QtCore.Qt.AlignRight)
            sizeItem.setFlags(sizeItem.flags() ^ QtCore.Qt.ItemIsEditable)
            createdDateItem = QtGui.QTableWidgetItem("%s" % dateCreated)
            createdDateItem.setTextAlignment(QtCore.Qt.AlignVCenter
                                             | QtCore.Qt.AlignRight)
            createdDateItem.setFlags(sizeItem.flags()
                                     ^ QtCore.Qt.ItemIsEditable)

            row = self.filesTable.rowCount()
            self.filesTable.insertRow(row)
            self.filesTable.setItem(row, 0, fileNameItem)
            self.filesTable.setItem(row, 1, createdDateItem)
            self.filesTable.setItem(row, 2, sizeItem)

        self.filesFoundLabel.setText(
            "%d file(s) found (Double click on a file to open it)" %
            len(files))
Beispiel #2
0
    def __init__(self, tex_file):
        self.__source = QtCore.QFileInfo(tex_file)
        self.__publish_dir = QtCore.QFileInfo()
        self.__publish = QtCore.QFileInfo()

        self.__state = TextureState.NotPub
        # Arnold option
        self.__arnold_static_option = '--oiio'
        self.__arnold_user_option = ''
Beispiel #3
0
 def dataDariFile(self):
     dialog = QtGui.QFileDialog(self)                        # memanggil objekFileDialog
     dialog.setFileMode(QtGui.QFileDialog.ExistingFiles)      # memanggil objek dengan semua tipe file
     dialog.setFilters(["*.mp3", "*.*"])
     if dialog.exec_() == QtGui.QDialog.Accepted:
         path = dialog.selectedFiles()
         for i in path :
             lokasi=QtCore.QFileInfo(i).absolutePath()
             tipe=QtCore.QFileInfo(i).suffix()
             if tipe.lower() == 'mp3' :
                 self.masukanFile([i,lokasi])
         if self.sedangDiputar == False:
             self.putarMusik()
    def updateFileMenu(self):
        #print "Updating file menu"
        self.fileMenu.clear()
        #Add all the actions, except quit
        self.addActions(self.fileMenu, self.fileMenuActions[:-1])
        recentFiles = []
        #append recent files to menu, if they still exist and are not currently open
        current = self.filename  #image that is currently open (will be None if none open)
        for fname in self.recentFiles:
            #print fname
            if fname != current and QtCore.QFile.exists(fname):
                recentFiles.append(fname)

        #Add a separator and the recent files, if applicable
        if recentFiles:
            self.fileMenu.addSeparator()
            for i, fname in enumerate(recentFiles):
                #define new action for clicking recent files in menu
                action = QtGui.QAction(QtGui.QIcon(":/icon.png"), "&{number} {name}". \
                                       format(number=i + 1, name=QtCore.QFileInfo(fname).fileName()), self)
                action.setData(
                    fname
                )  #how the filename is sneaked to loadFile, to which we are not here passing filename
                action.triggered.connect(
                    self.loadFile)  #connecting to slot to load file
                self.fileMenu.addAction(action)
        #Add separator, then the last menu action, Quit
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.fileMenuActions[-1])
Beispiel #5
0
    def __init__(self, fileName, parent=None):
        super(TabDialog, self).__init__(parent)

        fileInfo = QtCore.QFileInfo(fileName)

        tabWidget = QtGui.QTabWidget()
        tabWidget.addTab(GeneralTab(fileInfo), "General")
        tabWidget.addTab(PermissionsTab(fileInfo), "Config")
        tabWidget.addTab(ApplicationsTab(fileInfo), "Programmer")

        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok
                                           | QtGui.QDialogButtonBox.Cancel)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(tabWidget)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        # Titulo de la ventana
        self.setWindowTitle("PikBurn")
        # Icono en la ventana
        self.setWindowIcon(QtGui.QIcon('PikBurn4.png'))
Beispiel #6
0
    def build_file_tree(self, path, tree):
        """ Finds all files and folders in the given path and adds it to the tree 
        under the given tree item 
        """
        # If self.extensions is not empty, search only for files that end in those extensions, otherwise list everything
        if self.extensions:
            list_dir = [name for name in os.listdir(path) if os.path.isdir(
                os.path.join(path, name)) or name.lower().endswith(tuple(self.extensions))]
        else:
            list_dir = os.listdir(path)

        for element in list_dir:
            path_info = os.path.join(path, element)
            date = time.strftime('%m/%d/%y %H:%M',  time.localtime(os.path.getmtime(path_info)))
            parent_itm = QtGuiWidgets.QTreeWidgetItem(tree, [os.path.basename(element),date])
            parent_itm.setData(2, QtCore.Qt.EditRole, path_info)
            if os.path.isdir(path_info):
                parent_itm.setChildIndicatorPolicy(QtGuiWidgets.QTreeWidgetItem.ShowIndicator)
                # Activate the following line in order to recursively build the whole tree
                # self.build_file_tree(path_info, parent_itm)
            else:
                fileInfo = QtCore.QFileInfo(path_info)
                iconProvider = QtGuiWidgets.QFileIconProvider()
                icon = iconProvider.icon(fileInfo)
                parent_itm.setIcon(0, icon)
Beispiel #7
0
    def __init__(self, parent=None):
        super(MainDialog, self).__init__(parent)

        fileInfo = QtCore.QFileInfo(' ')

        self.tabWidget = QtGui.QTabWidget()
        self.tabWidget.addTab(InfoTab(fileInfo), "Book")
        self.tabWidget.addTab(FileTab(fileInfo), "Files")
        self.tabWidget.addTab(OptionsTab(fileInfo), "Options")
        self.tabWidget.currentChanged.connect(self.tabChanged)
        self.mainLayout = QtGui.QVBoxLayout()

        self.errorMessageDialog = QtGui.QErrorMessage(self)

        pubButton = QtGui.QPushButton(self.tr("&Publish"))
        pubButton.setDefault(True)

        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok
                                           | QtGui.QDialogButtonBox.Cancel)

        buttonBox.addButton(pubButton, QtGui.QDialogButtonBox.ActionRole)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        pubButton.clicked.connect(self.publish)

        self.mainLayout.addWidget(self.tabWidget)
        self.mainLayout.addWidget(buttonBox)
        self.setLayout(self.mainLayout)

        self.setWindowTitle("Epub3 Config")

        self.tabValue = 0
 def importSAX(self, fname):
     error = None
     fh = None
     try:
         handler = SaxMovieHandler(self)
         parser = QtXml.QXmlSimpleReader()
         parser.setContentHandler(handler)
         parser.setErrorHandler(handler)
         fh = QtCore.QFile(fname)
         input = QtXml.QXmlInputSource(fh)
         self.clear(False)
         if not parser.parse(input):
             raise ValueError(handler.error)
     except (IOError, OSError, ValueError) as e:
         error = "Failed to import: {}".format(e)
     except Exception as e:
         error = "Failed to import SAX: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__fname = ""
         self.__dirty = True
         return True, "Imported {} movie records from {}".format(
             len(self.__movies),
             QtCore.QFileInfo(fname).fileName())
 def importDOM(self, fname):
     dom = QtXml.QDomDocument()
     error = None
     fh = None
     try:
         fh = QtCore.QFile(fname)
         if not fh.open(QtCore.QIODevice.ReadOnly):
             raise IOError(fh.errorString())
         if not dom.setContent(fh):
             raise ValueError("could not parse XML")
     except (IOError, OSError, ValueError) as e:
         error = "Failed to import: {}".format(e)
     except Exception as e:
         error = "Failed to import DOM: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
     try:
         self.populateFromDOM(dom)
     except ValueError as e:
         return False, "Failed to import: {}".format(e)
     self.__fname = ""
     self.__dirty = True
     return True, "Imported {} movie records from {}".format(
         len(self.__movies),
         QtCore.QFileInfo(fname).fileName())
 def saveQTextStream(self):
     error = None
     fh = None
     try:
         fh = QtCore.QFile(self.__fname)  #fh: file handle
         if not fh.open(QtCore.QIODevice.WriteOnly):
             raise IOError(fh.errorString())
         stream = QtCore.QTextStream(fh)
         stream.setCodec(CODEC)
         for key, movie in self.__movies:
             stream << "{{MOVIE}} " << movie.title << "\n" \
                    << unicode(movie.year) << " " << unicode(movie.minutes) << " " \
                    << movie.acquired.toString(QtCore.Qt.ISODate) \
                    << "\n{NOTES}"
             if movie.notes:
                 stream << "\n" << movie.notes
             stream << "\n{{ENDMOVIE}}\n"
     except EnvironmentError as e:
         error = "Failed to save qt text stream: {0}".format(e)
     except Exception as e:
         error = "Failed to save qt text stream: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {} movie records to {}".format(
             len(self.__movies),
             QtCore.QFileInfo(self.__fname).fileName())
 def saveQDataStream(self):
     error = None
     file = None
     try:
         file = QtCore.QFile(self.__fname)  #qfile: chapter 6
         if not file.open(
                 QtCore.QIODevice.WriteOnly
         ):  #http://srinikom.github.io/pyside-docs/PySide/QtCore/QIODevice.html
             raise IOError(file.errorString())
         stream = QtCore.QDataStream(file)
         #Magic number in case you have same extension for different file format
         stream.writeInt32(MovieContainer.MAGIC_NUMBER)
         #File version in case you end up with a modified format
         stream.writeInt32(MovieContainer.FILE_VERSION)
         stream.setVersion(QtCore.QDataStream.Qt_4_6)
         for key, movie in self.__movies:
             stream.writeQString(movie.title)
             stream.writeInt16(movie.year)
             stream.writeInt16(movie.minutes)
             stream.writeQString(movie.acquired.toString(QtCore.Qt.ISODate))
             stream.writeQString(movie.notes)
     except EnvironmentError as e:
         error = "Failed to save Qt binary: {0}".format(e)
     except Exception as e:
         error = "Fail to save Qt binary: {0}".format(e)
     finally:
         if file is not None:
             file.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {} movie records to {}".format(
             len(self.__movies),
             QtCore.QFileInfo(self.__fname).fileName())
Beispiel #12
0
    def downloadFile(self):
        url = QtCore.QUrl(self.urlLineEdit.text())
        fileInfo = QtCore.QFileInfo(url.path())
        fileName = fileInfo.fileName()

        if not fileName:
            fileName = 'index.html'

        if QtCore.QFile.exists(fileName):
            ret = QtGui.QMessageBox.question(self, "HTTP",
                    "There already exists a file called %s in the current "
                    "directory." % fileName,
                    QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel,
                    QtGui.QMessageBox.Cancel)

            if ret == QtGui.QMessageBox.Cancel:
                return

            QtCore.QFile.remove(fileName)

        self.outFile = QtCore.QFile(fileName)
        if not self.outFile.open(QtCore.QIODevice.WriteOnly):
            QtGui.QMessageBox.information(self, "HTTP",
                    "Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
            self.outFile = None
            return

        if url.scheme().lower() == 'https':
            mode = QtNetwork.QHttp.ConnectionModeHttps
        else:
            mode = QtNetwork.QHttp.ConnectionModeHttp

        port = url.port()

        if port == -1:
            port = 0

        self.http.setHost(url.host(), mode, port)

        if url.userName():
            self.http.setUser(url.userName(), url.password())

        self.httpRequestAborted = False

        path = QtCore.QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/")
        if path:
            try:
                # Python v3.
                path = str(path, encoding='utf-8')
            except TypeError:
                # Python v2.
                path = str(path)
        else:
            path = '/'

        self.httpGetId = self.http.get(path, self.outFile)

        self.progressDialog.setWindowTitle("HTTP")
        self.progressDialog.setLabelText("Downloading %s." % fileName)
        self.downloadButton.setEnabled(False)
Beispiel #13
0
    def dataDariFolder(self):
        folder = QtGui.QFileDialog.getExistingDirectory(
            self, "Tentukan Folder", QtCore.QDir.currentPath())
        f = folder

        if folder:
            folder = QtCore.QDir(folder)
            file = folder.entryList(QtCore.QDir.Files | QtCore.QDir.NoSymLinks)

            ada = False
            for i in file:
                tipe = QtCore.QFileInfo(f + i).suffix()
                if tipe.lower() == 'mp3':
                    self.masukanFile([f + "/" + i, f])
                    ada = True
            if ada == False:
                QtGui.QMessageBox(
                    QtGui.QMessageBox.Critical, "Gagal Menambah Musik",
                    "File Musik tidak ditemukan pada folder :" + f + ""
                    "Silahkan pilih folder yang berisi file MP3.").exec_()

            elif self.sedangDiputar == False:
                pass
                self.putarMusik()
                self.perintahStop()
Beispiel #14
0
    def addObject(self, url):
        '''QUrlを受け取って、リストに追加するメソッド。'''
        filepath = url.path()  # QUrlからパスを取得。

        # Windowsから送られてくるuri-listは頭に/が付いているので
        # それをはずす。
        filepath = filepath[1:]

        # uri-listはパスの区切り文字が/なので、Windows風に¥に置き換える。
        filepath = filepath.replace('/', '\\')

        # 追加するアイテムを作成。---------------------------------------------------------
        row = self.rowCount()
        # ファイルパスのアイテムの追加。
        item = QtGui.QStandardItem()
        item.setText(filepath)
        self.setItem(row, 0, item)

        fileinfo = QtCore.QFileInfo(filepath)
        # ファイルの更新日時のアイテムの追加。
        item = QtGui.QStandardItem()
        item.setText(fileinfo.lastModified().toString('yyyy/MM/dd hh:mm:ss'))
        self.setItem(row, 1, item)

        # ファイルのサイズのアイテムを追加。
        item = QtGui.QStandardItem()
        item.setText(str(round(fileinfo.size() / 1024.0, 2)) + 'KB')
        self.setItem(row, 2, item)
    def runCalculix(self):
        if self.fea.ccx_binary_present is False:
            self.femConsoleMessage(
                "CalculiX can not be started. No or wrong CalculiX binary: {}".
                format(self.fea.ccx_binary))
            # TODO deactivate the run button
            return
        # print("runCalculix")
        self.Start = time.time()

        self.femConsoleMessage("CalculiX binary: {}".format(
            self.fea.ccx_binary))
        self.femConsoleMessage("CalculiX input file: {}".format(
            self.fea.inp_file_name))
        self.femConsoleMessage("Run CalculiX...")

        FreeCAD.Console.PrintMessage("run CalculiX at: {} with: {}\n".format(
            self.fea.ccx_binary, self.fea.inp_file_name))
        # change cwd because ccx may crash if directory has no write permission
        # there is also a limit of the length of file names so jump to the document directory
        self.cwd = QtCore.QDir.currentPath()
        fi = QtCore.QFileInfo(self.fea.inp_file_name)
        QtCore.QDir.setCurrent(fi.path())
        self.Calculix.start(self.fea.ccx_binary, ["-i", fi.baseName()])

        QApplication.restoreOverrideCursor()
Beispiel #16
0
    def __init__(self):
        super().__init__()

        self.name = sis_name
        self.version = sis_version

        # setup default project folder
        self.projects_folder = self.here

        self.setWindowTitle('%s v.%s' % (self.name, self.version))
        # noinspection PyArgumentList
        _app = QtCore.QCoreApplication.instance()
        _app.setApplicationName('%s' % self.name)
        _app.setOrganizationName("HydrOffice")
        _app.setOrganizationDomain("hydroffice.org")

        # set icons
        icon_info = QtCore.QFileInfo(
            os.path.join(self.here, 'media', 'favicon.png'))
        self.setWindowIcon(QtGui.QIcon(icon_info.absoluteFilePath()))
        if (sys.platform == 'win32') or (os.name is "nt"):

            try:
                # This is needed to display the app icon on the taskbar on Windows 7
                import ctypes
                app_id = '%s v.%s' % (self.name, self.version)
                ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                    app_id)

            except AttributeError as e:
                logger.debug("Unable to change app icon: %s" % e)

        self.panel = controlpanel.ControlPanel()
        self.setCentralWidget(self.panel)
Beispiel #17
0
 def start_ccx(self):
     import multiprocessing
     import os
     import subprocess
     self.ccx_stdout = ""
     self.ccx_stderr = ""
     if self.inp_file_name != "" and self.ccx_binary_present:
         ont_backup = os.environ.get('OMP_NUM_THREADS')
         if not ont_backup:
             ont_backup = ""
         _env = os.putenv('OMP_NUM_THREADS',
                          str(multiprocessing.cpu_count()))
         # change cwd because ccx may crash if directory has no write permission
         # there is also a limit of the length of file names so jump to the document directory
         cwd = QtCore.QDir.currentPath()
         f = QtCore.QFileInfo(self.inp_file_name)
         QtCore.QDir.setCurrent(f.path())
         p = subprocess.Popen(
             [self.ccx_binary, "-i ", f.baseName()],
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE,
             shell=False,
             env=_env)
         self.ccx_stdout, self.ccx_stderr = p.communicate()
         os.putenv('OMP_NUM_THREADS', ont_backup)
         QtCore.QDir.setCurrent(cwd)
         return p.returncode
     return -1
Beispiel #18
0
 def start_ccx(self):
     import multiprocessing
     import os
     import subprocess
     self.ccx_stdout = ""
     self.ccx_stderr = ""
     if self.inp_file_name != "" and self.ccx_binary_present:
         ont_backup = os.environ.get('OMP_NUM_THREADS')
         self.ccx_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Ccx")
         num_cpu_pref = self.ccx_prefs.GetInt("AnalysisNumCPUs", 1)  # If number of CPU's specified
         if not ont_backup:
             ont_backup = str(num_cpu_pref)
         if num_cpu_pref > 1:
             _env = os.putenv('OMP_NUM_THREADS', str(num_cpu_pref))  # if user picked a number use that instead
         else:
             _env = os.putenv('OMP_NUM_THREADS', str(multiprocessing.cpu_count()))
         # change cwd because ccx may crash if directory has no write permission
         # there is also a limit of the length of file names so jump to the document directory
         cwd = QtCore.QDir.currentPath()
         f = QtCore.QFileInfo(self.inp_file_name)
         QtCore.QDir.setCurrent(f.path())
         p = subprocess.Popen([self.ccx_binary, "-i ", f.baseName()],
                              stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                              shell=False, env=_env)
         self.ccx_stdout, self.ccx_stderr = p.communicate()
         os.putenv('OMP_NUM_THREADS', ont_backup)
         QtCore.QDir.setCurrent(cwd)
         return p.returncode
     return -1
Beispiel #19
0
    def findMdiChild(self, fileName):
        canonicalFilePath = QtCore.QFileInfo(fileName).canonicalFilePath()

        for window in self.mdiArea.subWindowList():
            if window.widget().currentFile() == canonicalFilePath:
                return window
        return None
Beispiel #20
0
	def on_buttontransnew_clicked (self):

		model = self.ui.transview.model()

		nc = NewConvert (self.params['LastTransferPath'], self.params['LastTransferSrcPath'])
		if nc.exec_() == QtGui.QDialog.Accepted:

			files = nc.files
			newpath = nc.transferpath

			self.params['LastTransferPath'] = newpath
			self.rpcworker.renewparamssignal.emit (self.params)

			while len (files) > 0:
				newfile = QtCore.QFileInfo (files.pop (0))
				row = model.rowCount()
				model.insertRow (row)

				model.setData (model.index (row, 0), newfile.fileName())
				model.setData (model.index (row, 1), 0)
				model.setData (model.index (row, 2), self.tr ("Verifying File Parameters..."))
				model.setData (model.index (row, 3), newpath)

				checker = MediaFileChecker (QtCore.QDir.toNativeSeparators (newfile.absoluteFilePath()), len (self.checkers))
				checker.discoveredsignal.connect (self.mediafilediscovered)
				checker.finished.connect (checker.deleteLater)
				self.checkers.append ({"worker": checker, "operation": "Transcode",
					"params": (QtCore.QDir.toNativeSeparators (newfile.absoluteFilePath()), newpath, row, self)})
				self.transcoding.append ({"worker": None, "status": TransTaskVerifying})
				checker.startworker()
Beispiel #21
0
    def httpRequestFinished(self, requestId, error):
        if self.httpRequestAborted:
            if self.outFile is not None:
                self.outFile.close()
                self.outFile.remove()
                self.outFile = None

            self.progressDialog.hide()
            return

        if requestId != self.httpGetId:
            return

        self.progressDialog.hide()
        self.outFile.close()

        if error:
            self.outFile.remove()
            QtGui.QMessageBox.information(self, self.tr("HTTP"),
                                          self.tr("Download failed: %s.")
                                          % (self.http.errorString()))
        else:
            fileName = QtCore.QFileInfo(QtCore.QUrl(self.urlLineEdit.text()).path()).fileName()
            self.statusLabel.setText(self.tr("Downloaded %s to current directory.") % (fileName))

        self.downloadButton.setEnabled(True)
        self.outFile = None
Beispiel #22
0
    def downloadFile(self):
        url = QtCore.QUrl(self.urlLineEdit.text())
        fileInfo = QtCore.QFileInfo(url.path())
        fileName = fileInfo.fileName()

        if QtCore.QFile.exists(fileName):
            QtGui.QMessageBox.information(self, self.tr("HTTP"), self.tr(
                                          "There already exists a file called %s "
                                          "in the current directory.") % (fileName))
            return

        self.outFile = QtCore.QFile(fileName)
        if  not self.outFile.open(QtCore.QIODevice.WriteOnly):
            QtGui.QMessageBox.information(self, self.tr("HTTP"),
                                          self.tr("Unable to save the file %(name)s: %(error)s.")
                                          % {'name': fileName,
                                             'error': self.outFile.errorString()})
            self.outFile = None
            return

        if url.port() != -1:
            self.http.setHost(url.host(), url.port())
        else:
            self.http.setHost(url.host(), 80)
        if url.userName():
            self.http.setUser(url.userName(), url.password())

        self.httpRequestAborted = False
        self.httpGetId = self.http.get(url.path(), self.outFile)

        self.progressDialog.setWindowTitle(self.tr("HTTP"))
        self.progressDialog.setLabelText(self.tr("Downloading %s.") % (fileName))
        self.downloadButton.setEnabled(False)
    def updateDefault(self):

        for name, role in self.objectslist.items():
            role = role[0]
            obj = FreeCAD.ActiveDocument.getObject(name)
            if obj:
                if (not self.form.onlyVisible.isChecked()
                    ) or obj.ViewObject.isVisible():
                    it1 = QtGui.QStandardItem(obj.Label)
                    if QtCore.QFileInfo(":/icons/Arch_" + obj.Proxy.Type +
                                        "_Tree.svg").exists():
                        icon = QtGui.QIcon(":/icons/Arch_" + obj.Proxy.Type +
                                           "_Tree.svg")
                    else:
                        icon = QtGui.QIcon(":/icons/Arch_Component.svg")
                    it1.setIcon(icon)
                    it1.setToolTip(obj.Name)
                    it2 = QtGui.QStandardItem(role)
                    if hasattr(obj, "IfcType"):
                        r = obj.IfcType
                    else:
                        r = obj.IfcRole
                    if role != r:
                        it2.setIcon(QtGui.QIcon(":/icons/edit-edit.svg"))
                    it3 = self.getSearchResults(obj)
                    if it3:
                        self.model.appendRow([it1, it2, it3])
Beispiel #24
0
    def addImage(self):
        fileNames, filters = QtGui.QFileDialog.getOpenFileNames(
            self, "Open Images", '',
            "Images (*.png *.xpm *.jpg);;All Files (*)")

        for fileName in fileNames:
            row = self.imagesTable.rowCount()
            self.imagesTable.setRowCount(row + 1)

            imageName = QtCore.QFileInfo(fileName).baseName()
            item0 = QtGui.QTableWidgetItem(imageName)
            item0.setData(QtCore.Qt.UserRole, fileName)
            item0.setFlags(item0.flags() & ~QtCore.Qt.ItemIsEditable)

            item1 = QtGui.QTableWidgetItem("Normal")
            item2 = QtGui.QTableWidgetItem("Off")

            if self.guessModeStateAct.isChecked():
                if '_act' in fileName:
                    item1.setText("Active")
                elif '_dis' in fileName:
                    item1.setText("Disabled")
                elif '_sel' in fileName:
                    item1.setText("Selected")

                if '_on' in fileName:
                    item2.setText("On")

            self.imagesTable.setItem(row, 0, item0)
            self.imagesTable.setItem(row, 1, item1)
            self.imagesTable.setItem(row, 2, item2)
            self.imagesTable.openPersistentEditor(item1)
            self.imagesTable.openPersistentEditor(item2)

            item0.setCheckState(QtCore.Qt.Checked)
Beispiel #25
0
    def importDialog(self):
        """ Launch the import dialog
		"""
        # try and set last import directory
        settings = QtCore.QSettings()
        importDir = settings.value("options/importdirectory")

        if not importDir:
            importDir = QtCore.QDir.homePath()

        dialog = QtGui.QFileDialog(self, 'Open File', importDir, "*.csv")
        dialog.setFileMode(QtGui.QFileDialog.ExistingFiles)

        if not dialog.exec_():
            return

        fileNames = [
            QtCore.QFileInfo(f).fileName() for f in dialog.selectedFiles()
        ]

        # Save the settings for next time
        settings.setValue('options/importdirectory',
                          dialog.directory().absolutePath())

        dialog = dialogs.ImportDialog(dialog.selectedFiles(), self)
        dialog.setWindowTitle(', '.join(fileNames))
        dialog.accepted.connect(self.importClosed)
        dialog.setModal(False)
        dialog.show()
Beispiel #26
0
    def __init__(self, main_win, db):
        super(AbstractWidget, self).__init__()
        if type(db) != SetupDb:
            raise RuntimeError("Passed invalid settings db object: %s" %
                               type(db))
        self.main_win = main_win
        self.db = db

        # set palette
        style_info = QtCore.QFileInfo(
            os.path.join(self.here, 'styles', 'widget.stylesheet'))
        style_content = open(style_info.filePath()).read()
        self.setStyleSheet(style_content)

        self.setContentsMargins(0, 0, 0, 0)

        # add a frame
        self.frame = QtGui.QFrame()
        self.setCentralWidget(self.frame)

        # progress dialog
        self.progress = QtGui.QProgressDialog(self)
        self.progress.setWindowTitle("Processing")
        self.progress.setCancelButtonText("Abort")
        self.progress.setWindowModality(QtCore.Qt.WindowModal)
 def addPixmap(self):
     path = QtCore.QFileInfo(self.filename).path() if self.filename else "."
     fname = QtGui.QFileDialog.getOpenFileName(
         self, "Page Designer - Add Pixmap", path,
         "Pixmap Files (*.bmp *.jpg *.png *.xpm)")[0]
     if not fname:
         return
     self.createPixmapItem(QtGui.QPixmap(fname), self.position())
Beispiel #28
0
    def updateByMaterial(self):

        groups = {}
        for name, rolemat in self.objectslist.items():
            role = rolemat[0]
            mat = rolemat[1]
            if not mat:
                mat = "Undefined"
            obj = FreeCAD.ActiveDocument.getObject(name)
            if obj:
                if (not self.form.onlyVisible.isChecked()
                    ) or obj.ViewObject.isVisible():
                    groups.setdefault(mat, []).append([name, role])

        for group in groups.keys():
            grlabel = "Undefined"
            if group != "Undefined":
                matobj = FreeCAD.ActiveDocument.getObject(group)
                if matobj:
                    grlabel = matobj.Label
            s1 = grlabel + " (" + str(len(groups[group])) + ")"
            top = QtGui.QStandardItem(s1)
            self.model.appendRow(
                [top, QtGui.QStandardItem(),
                 QtGui.QStandardItem()])
            for name, role in groups[group]:
                obj = FreeCAD.ActiveDocument.getObject(name)
                if obj:
                    it1 = QtGui.QStandardItem(obj.Label)
                    if QtCore.QFileInfo(":/icons/Arch_" + obj.Proxy.Type +
                                        "_Tree.svg").exists():
                        icon = QtGui.QIcon(":/icons/Arch_" + obj.Proxy.Type +
                                           "_Tree.svg")
                    else:
                        icon = QtGui.QIcon(":/icons/Arch_Component.svg")
                    it1.setIcon(icon)
                    it1.setToolTip(obj.Name)
                    it2 = QtGui.QStandardItem(role)
                    if role != obj.IfcRole:
                        it2.setIcon(QtGui.QIcon(":/icons/edit-edit.svg"))
                    mat = ""
                    matlabel = ""
                    if group != "Undefined":
                        matobj = FreeCAD.ActiveDocument.getObject(group)
                        if matobj:
                            matlabel = matobj.Label
                            mat = matobj.Name
                    it3 = QtGui.QStandardItem(matlabel)
                    it3.setToolTip(mat)
                    omat = ""
                    if hasattr(obj, "Material") and obj.Material:
                        omat = obj.Material.Name
                        if omat != mat:
                            it3.setIcon(QtGui.QIcon(":/icons/edit-edit.svg"))
                    top.appendRow([it1, it2, it3])
            top.sortChildren(0)
        self.form.tree.expandAll()
        self.spanTopLevels()
Beispiel #29
0
    def findMainWindow(self, fileName):
        canonicalFilePath = QtCore.QFileInfo(fileName).canonicalFilePath()

        for widget in QtGui.qApp.topLevelWidgets():
            if isinstance(widget,
                          MainWindow) and widget.curFile == canonicalFilePath:
                return widget

        return None
Beispiel #30
0
 def add(self, filename):
     #print "Adding watch: " + filename
     if os.path.isfile(filename):
         fileinfo = QtCore.QFileInfo(filename)
         self.files[fileinfo.canonicalFilePath()] = fileinfo.lastModified()
         if fileinfo.canonicalFilePath() in self.filecount:
             self.filecount[fileinfo.canonicalFilePath()] += 1
         else:
             self.filecount[fileinfo.canonicalFilePath()] = 1