Reader small image

You're reading from  FreeCAD

Product typeBook
Published inSep 2012
PublisherPackt
ISBN-139781849518864
Edition1st Edition
Concepts
Right arrow
Authors (2):
Brad Collette
Brad Collette
author image
Brad Collette

Brad Collette once designed software for a big company but doesn't like to remember that. These days, he is an entrepreneur, hobbyist, jack-of-all-trades, and a gentleman farmer. He is engaged in a multi-year project to raise two hacker sons. He has contributed to numerous open source projects and is an organizing member of Columbia Gadget Works, central Missouri's finest hackerspace.
Read more about Brad Collette

Daniel Falck
Daniel Falck
author image
Daniel Falck

Daniel Falck has over 25 years experience in manufacturing, machining, CAD, CAM, and computer programming. He has worked for Gibson Guitar doing design and prototyping for over 14 years. Currently, he runs the Prototype machine shop at King Cycle Group, in Portland, Oregon (USA), where bicycle components are manufactured. His home shop is full of CNC machining equipment that he uses to create guitar parts for customers, using open source software running on Linux. Over the past 10 years he has worked with open source manufacturing software such as Linuxcnc, APT360, HeeksCAD, FreeCAD, and a myriad of specialized python scripts.
Read more about Daniel Falck

View More author details
Right arrow

Creating a custom dialog to automate a task (Become an expert)


The Python programming language in FreeCAD allows us to use PyQt4 or PySide to add our own widgets to make custom graphical user interfaces. In this recipe, we will create a dialog box that lets us create a simple box.

Getting ready

If the Draft workbench is functioning properly in FreeCAD, then you already have PyQt4 installed on your computer. Open a new document, so that we have space for our 3D box to appear.

How to do it...

The following is some code that will make a dialog pop-up, which lets us create a 3D solid box with a few parameters:

  1. Type the following code into the Python console exactly as shown. Python is case and indent sensitive. Be consistent on indentation. We will use four spaces per indent here. An intent looks like a tab in this text. I have added \ (backslashes) to some lines that won't fit on the printed page in their complete form.

    from PyQt4 import QtGui,QtCore
    import Part,FreeCAD
    from FreeCAD import Base,Vector
    
    class BoxExample(QtGui.QWidget):
        def __init__(self):
            super(BoxExample, self).__init__()
            self.initUI()
        def initUI(self):
            self.setGeometry(100, 100,300, 200)
            self.setWindowTitle('Make a Box!')
            self.lengthLabel = QtGui.QLabel("Length: ",self)
            self.lengthLabel.move(50, 15)
            self.length = QtGui.QLineEdit(self)
            self.length.move(100, 15)
            self.widthLabel = QtGui.QLabel("Width: ",self)
            self.widthLabel.move(50, 50)
            self.width = QtGui.QLineEdit(self)
            self.width.move(100, 50)
            self.heightLabel = QtGui.QLabel("Height: ",self)
            self.heightLabel.move(50, 85)
            self.height = QtGui.QLineEdit(self)
            self.height.move(100, 85)
            self.centered=QtGui.QCheckBox("Center on XY",self)
            self.centered.move(80, 115)
            self.centerbox = False
            self.centered.stateChanged.connect(self.changeState)
            self.okButton = QtGui.QPushButton("Create Box",self)
            self.okButton.move(160, 150)
            self.show()
            QtCore.QObject.connect \
    (self.okButton, QtCore.SIGNAL("pressed()"),self.box)  
        def changeState(self, state):
            console=FreeCAD.Console
            if state == QtCore.Qt.Checked:
                console.PrintMessage("Box will be centered\n")
                self.centerbox = True
            else:
                self.centerbox = False
        def box(self):
            l = float(self.length.text())
            w = float(self.width.text())
            h = float(self.height.text())
            if self.centerbox == True:
                box = Part.makeBox(l,w,h)
                box.translate(Base.Vector(-l/2,-w/2,0))
            else:
                box = Part.makeBox(l,w,h)
            Part.show(box)
    
    d = BoxExample() 
  2. Press the Enter key twice after typing in the last line.

  3. When the dialog box pops up, fill in the values and click on the Create Box button. A simple 3D box should appear in the FreeCAD document. It looks similar to the following screenshot:

How it works...

We start by creating a class that holds all of our dialog box functions:

class BoxExample(QtGui.QWidget):

The code within the BoxExample class that is part of the function def initUI(self): is used to set up the widgets for our dialog. Lines that have QtGui.QLabel in them let us label the textboxes that are made with QtGui.QLineEdit(self). There is a checkbox and a button towards the end of the function in the form of QtGui.QCheckBox and QtGui.QPushButton respectively. def changeState(self, state): is used to see if our Center on XY checkbox is checked.

The following lines of code are used to connect the button labeled Create Box to the next function:

QtCore.QObject.connect \
(self.okButton, QtCore.SIGNAL("pressed()"),self.box)

I used the \ continuation character to fit one long line of code onto the formatted text of this book, so these two lines appear to be one to Python.

The def box(self) function does the work to create the 3D solid box in the document. box = Part.makeBox(l,w,h) creates the box and Part.show(box) makes it appear in our document.

Within FreeCAD Python scripting, we don't use a main call, like we would have if we were making a standalone application. Instead we use d = BoxExample() to invoke and show our BoxExample() class. This is what turns our dialog box on.

There's more...

To learn more about dialog creation for FreeCAD go to https://sourceforge.net/apps/mediawiki/free-cad/index.php?title=Dialog_creation.

Learn more about Python and PyQt programming

One of the first places that a new Python programmer should check out is the official Python documentation website available at http://python.org/doc/.

There is also a good intro to PyQt programming available at http://zetcode.com/tutorials/pyqt4/firstprograms/.

Make things easier by using Qt Designer

To make programming dialogs a lot easier, you will want to use Qt Designer, a graphical dialog creation tool. It will let you create dialogs with a graphical editor that can be converted into Python code. If you are using Ubuntu Linux as your operating system, look in Synaptic for qtdesigner.

This following web page gives a good introduction to creating dialogs for FreeCAD:

https://sourceforge.net/apps/mediawiki/free-cad/index.php?title=Dialog_creation

Previous PageNext Page
You have been reading a chapter from
FreeCAD
Published in: Sep 2012Publisher: PacktISBN-13: 9781849518864
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Brad Collette

Brad Collette once designed software for a big company but doesn't like to remember that. These days, he is an entrepreneur, hobbyist, jack-of-all-trades, and a gentleman farmer. He is engaged in a multi-year project to raise two hacker sons. He has contributed to numerous open source projects and is an organizing member of Columbia Gadget Works, central Missouri's finest hackerspace.
Read more about Brad Collette

author image
Daniel Falck

Daniel Falck has over 25 years experience in manufacturing, machining, CAD, CAM, and computer programming. He has worked for Gibson Guitar doing design and prototyping for over 14 years. Currently, he runs the Prototype machine shop at King Cycle Group, in Portland, Oregon (USA), where bicycle components are manufactured. His home shop is full of CNC machining equipment that he uses to create guitar parts for customers, using open source software running on Linux. Over the past 10 years he has worked with open source manufacturing software such as Linuxcnc, APT360, HeeksCAD, FreeCAD, and a myriad of specialized python scripts.
Read more about Daniel Falck