Example #1
0
class MainWindow(QMainWindow):
    
    # Create the menu for the main window. Contains a button to connect, 
    # disconnect and exit.
    def makeMenu(self):
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        connectAction = QtGui.QAction('&Connect', self)
        connectAction.setShortcut('Ctrl+C')
        connectAction.setStatusTip('Connect to server')
        connectAction.triggered.connect(self.connect)
        disconnectAction = QtGui.QAction('&Disconnect', self)
        disconnectAction.setShortcut('Ctrl+D')
        disconnectAction.setStatusTip('Disconnect to server')
        disconnectAction.triggered.connect(self.disconnect)
        exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.rejected)
        fileMenu.addAction(connectAction)
        fileMenu.addAction(disconnectAction)
        fileMenu.addAction(exitAction)

    # Creates a window that is used by the user to input which server 
    # to connect to.
    def makeConnectWindow(self):
        
        self.dialog = QDialog()
        self.dialog.setWindowTitle('Connect to server')
        self.qform = QFormLayout(self.dialog)
        self.qform.addRow(QLabel("Connect (Blank for localhost)"))
        self.list = QListWidget()
        self.ipLabel = QLabel('IP')
        self.ip = QLineEdit(self.dialog)
        self.portLabel = QLabel('Port')
        self.port = QLineEdit(self.dialog)
        self.qform.addRow(self.ipLabel, self.ip)
        self.qform.addRow(self.portLabel, self.port)
        self.buttonBox = QDialogButtonBox(Qt.Horizontal)
        self.connectButton = QPushButton("&Connect")
        self.connectButton.setDefault(True)
        self.cancelButton = QPushButton("&Cancel")
        self.cancelButton.setCheckable(True)
        self.cancelButton.setAutoDefault(False)
        self.buttonBox.addButton(self.connectButton, QDialogButtonBox.AcceptRole)
        self.buttonBox.addButton(self.cancelButton, QDialogButtonBox.RejectRole)
        self.buttonBox.accepted.connect(self.accepted)
        self.buttonBox.rejected.connect(self.rejected)
        self.qform.addRow(self.buttonBox)
    
    # Initiate Window
    def __init__(self, parent=None):
        
        super(MainWindow, self).__init__(parent)
        self.tab_widget = tab_widget(self)
        self.setWindowTitle('Book Library (Disconnected)')
        self.setCentralWidget(self.tab_widget)
        self.centerOnScreen()
        
        self.makeMenu()
        
        self.makeConnectWindow()
        
        self.dialog.show()        
        self.show()
 
    # Connect to server
    def connect(self, HOST, PORT):        
        global sock
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((HOST,PORT))
            sock.settimeout(10)
            self.setWindowTitle("Book Library (Connected)")
            self.dialog.hide()
        except:
            self.dialog.show()
            self.setWindowTitle("Book Library (Disconnected)")
            QMessageBox.warning(self, "Failure", "Connection failed")
       
    # Function for when QDialog windows accepted button is pressed, used 
    # gets the ip and port input and connects to that server
    def accepted(self):
 
        ip = str(self.ip.text())
        port = str(self.port.text())
        if len(ip.lstrip()) > 0 and len(port.lstrip()) > 0:
            try:
                HOST = ip.lstrip()
                PORT = int(port.lstrip())
            except:
                QMessageBox.warning(self, "Failure", "Failed connecting to server")
                HOST = ''  # Symbolic name meaning the local host    
                PORT = 24069  # Arbitrary non-privileged port
        else:
            HOST = ''  # Symbolic name meaning the local host    
            PORT = 24069  # Arbitrary non-privileged port
        print HOST
        print PORT
        self.connect(HOST, PORT)
    
    # Function used when the user clicks on the cancel button in the 
    # QDialog window.
    def rejected(self):
        if self.dialog.isHidden():
            self.disconnect()
        sys.exit(0)
        

    # Disconnect from the server
    def disconnect(self):
        global sock
        
        try:
            sock.send("EXIT")
            data = sock.recv(1024)
            if data == "200 OK":
                sock.close()
                self.setWindowTitle('Book Library (Disconnected)')
                self.dialog.show()
        except:
            self.dialog.hide()
            QMessageBox.warning(self, "Error", "Failed to disconnect from server")
        
    
    # Send BookData to server.
    def sendBookData(self, author, title, genre, genre2, dateRead, grade, comments):
        if self.dialog.isHidden():
            global sock
            try:
                sock.send('SEND_ROW_DATA "' + author + '", "' + title + '", "' + genre + '", "' + genre2 + 
                     '", ' + dateRead + ', ' + grade + ', "' + comments + '"\n')
                data = sock.recv(1024)
                if data == '200 OK':
                    dialog = QMessageBox()
                    dialog.setText("Data added successfully")
                    dialog.exec_()
            except socket.timeout:
                dialog = QMessageBox()
                dialog.set
                dialog.setText("Connection timed out...")
                dialog.exec_()
            except:
                self.parent().setWindowTitle("Book Library (Disconnected)")
                dialog = QMessageBox()
                dialog.set
                dialog.setText("Connect to server to be able to send data.")
                dialog.exec_()
        else:
            dialog = QMessageBox()
            dialog.set
            dialog.setText("Connect to server to be able to send data.")
            dialog.exec_()
   
    
    # Moves the window to the center of the screen
    def centerOnScreen (self):  
        resolution = QtGui.QDesktopWidget().screenGeometry()
        self.move((resolution.width() / 2) - (self.frameSize().width() / 2),
                  (resolution.height() / 2) - (self.frameSize().height() / 2))

    # Event when user clicks the windows cross.
    def closeEvent(self, event):
        if self.dialog.isHidden():
            self.disconnect()
        sys.exit(0)