How to close windows in pyqtgraph

2.8k views Asked by At

I want to close all of my pyqtgraph widgets. I followed the suggestions here, but they didn't work. Here's my code

def makeWindows(amp, title):
    WYSIZE = 800
    WXSIZE = 800
    XSIZE = 200
    YSIZE = 200
    TSIZE = 100
    STEPS = np.array([0.0, 0.25, 0.5,.75, 1.0])

    first = "00007F"
    blue = "007FFF"
    cyan = "7FFF7F"
    yellow = "FF7F00"
    red = "7F0000"


    win = QtGui.QMainWindow()
    win.resize(WXSIZE, WYSIZE)
    CLRS = [first,blue, cyan, yellow, red]

    for i,item in enumerate(CLRS):
        CLRS[i] = list(ord(c) for c in item.decode('hex')) 
        CLRS[i].append(255)

    clrmp = pg.ColorMap(STEPS, np.array( CLRS))


    lut = clrmp.getLookupTable()

    plt = pg.PlotItem(labels={'bottom': ('samples', 'm'), 'left': ('stuff', 'm')}, title = title)
    plt.setAspectLocked(False)
    imv = pg.ImageView(view = plt)
    win.setCentralWidget(imv)
    #imv.setLevels(3,6)
    imv.ui.histogram.gradient.setColorMap(clrmp)
    imv.setImage(amp)
    win.show()

    return win, imv


def main():
    app = QtGui.QApplication([])


    win1, imv1 = makeWindows(amp, "amp")

    if __name__ == '__main__':
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):            
            status = QtGui.QApplication.instance().exec_()

            #sys.exit(status)
            imv1.close()
            win1.close()
            app.closeAllWindows()

main()

After I execute this window, all of the windows should be closed, but they are not. I'm not even getting the image to close.

Thanks for your help

UPDATE:

My original intention was to create a way to allow the user to close all windows when they inserted a keyboard interrupt (ctrl-c)

I added the following function

def close_all():
    app = QtGui.QApplication([])
    app.closeAllWindows()

and added the following lines towards the end of makeWindows

sh = QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"),imv,None, close_all)
sh.setContext(QtCore.Qt.ApplicationShortcut)

This makes it so that anytime a user presses Ctrl+c when a window is in focus, it closes all of the windows

1

There are 1 answers

4
Luke On BEST ANSWER

Your call to QApplication.exec_() does not return--it blocks until the application has exited (in this case, the application exits when you close the window). So the lines that would close the window are not called until after you have already closed it.