PySide: Using standard system Icons

You can add Icons to many types of QWidgets. PySide provides you with a method to access the native system icons. A complete list of icons can be found here:PySide.QtGui.PySide.QtGui.QStyle.StandardPixmap

To apply the QIcon you need to

btn = QPushButton('Folder')
style = btn.style()
icon = style.standardIcon(QStyle.SP_DirIcon)
btn.setIcon(icon)
#or short:
btn.setIcon(btn.style().standardIcon(QStyle.SP_DirIcon))

Here a small example:

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Widget(QWidget):
    
    def __init__(self, parent= None):
        super(Widget, self).__init__()
        
        btn_folder = QPushButton('Folder')
        btn_folder.setIcon(self.style().standardIcon(QStyle.SP_DirIcon))
        
        btn_one = QPushButton('Play')
        btn_one.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        
        btn_two = QPushButton('Stop')
        btn_two.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        
        btn_three = QPushButton('Pause')
        btn_three.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
        
        layout = QHBoxLayout()
        layout.addWidget(btn_folder)
        layout.addWidget(btn_one)
        layout.addWidget(btn_two)
        layout.addWidget(btn_three)
        
        self.setLayout(layout)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    dialog = Widget()
    dialog.show()

    app.exec_()

PySide: QMessageBox with QCheckBox

The QMessageBox is very useful for creating standard filesystem dialogs (it even comes with alert sounds) and is limited to display an icon, text and standard buttons. If you want to add something extra like a checkbox for “do not ask me again”, you need to extend the base class.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class DialogWithCheckBox(QMessageBox):

    def __init__(self, parent= None):
        super(DialogWithCheckBox, self).__init__()

        self.checkbox = QCheckBox()
        #Access the Layout of the MessageBox to add the Checkbox
        layout = self.layout()
        layout.addWidget(self.checkbox, 1,2)

    def exec_(self, *args, **kwargs):
        """
        Override the exec_ method so you can return the value of the checkbox
        """
        return QMessageBox.exec_(self, *args, **kwargs), self.checkbox.isChecked()

class ExampleCheckbox(DialogWithCheckBox):

    def __init__(self, parent=None):
        super(ExampleCheckbox, self).__init__()
        self.setWindowTitle("Dialog with CheckBox")
        self.setText("Isn't this checkbox beautiful?")
        self.checkbox.setText("Do not ask again")
        self.setStandardButtons(QMessageBox.Cancel |QMessageBox.Ok)
        self.setDefaultButton(QMessageBox.Cancel)
        self.setIcon(QMessageBox.Warning)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    dialog = ExampleCheckbox()
    answer = dialog.exec_()

    # Example how to handle the response
    if answer[1] == True:
        if answer[0] == int(QMessageBox.Ok):
            print ("Ok button pressed")
        print ("handle checkbox has been activated")
    else:
        print ("handle checkbox not activated")

    app.exec_() 

PySide: Rightclick Button Menu

PySide (www.pyside.org) is an awesome Framework that allows you to use Qt with Python. Installation is as straightforward as typing

pip install pyside

I will be creating a menu that opens with a right click. This menu is called “Context Menu” in QT. In this example, the right-click menu on the button removes the button at runtime.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class RightClickMenuButton(QPushButton):

    def __init__(self, name, parent = None):
        super(RightClickMenuButton, self).__init__(name)

        self.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.addMenuActions();

    def addMenuActions(self):
        delete = QAction(self)
        delete.setText("remove")
        delete.triggered.connect(self.removeButton)
        self.addAction(delete)

    def removeButton(self):
        self.deleteLater()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = QWidget()
    test.resize(250, 150)

    layout = QHBoxLayout()
    layout.addWidget(RightClickMenuButton("Test Btn"))
    test.setLayout(layout)

    test.show()
    app.exec_()

Java GUI: Using AbstractTableModel

Using the AbstractTableModel the easiest way to store the table data is to use a Vector of Vectors. You have to implement additional functions to insert new data.

Here is the example:

import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class AbstractTableDemo extends JPanel {

 public AbstractTableDemo() {
  super(new GridLayout(1, 0));

  final JTable table = new JTable(new MyTableModel());
  table.setPreferredScrollableViewportSize(new Dimension(500, 70));
  table.setFillsViewportHeight(true);

  Object[] values = {
   "String",
   10,
   20.0,
   30.2,
   new Boolean(false)
  };
  MyTableModel a = (MyTableModel) table.getModel();
  a.insertData(values);

  //Create the scroll pane and add the table to it.
  JScrollPane scrollPane = new JScrollPane(table);

  //Add the scroll pane to this panel.
  add(scrollPane);
 }

 class MyTableModel extends AbstractTableModel {
  private String[] columnNames = {
   "Title A",
   "Title B",
   "Title C",
   "Title D",
   "Title E"
  };

  private Vector data = new Vector();

  public final Object[] longValues = {
   "",
   new Integer(20),
   new Float(20),
   new Float(20),
   Boolean.TRUE
  };

  @Override
  public int getColumnCount() {
   return columnNames.length;
   private String[] columnNames = {
    "Title A",
    "Title B",
    "Title C",
    "Title D",
    "Title E"
   };

   private Vector data = new Vector();

   public final Object[] longValues = {
    "",
    new Integer(20),
    new Float(20),
    new Float(20),
    Boolean.TRUE
   };

   @Override
   public int getColumnCount() {
    return columnNames.length;
   }

   @Override
   public int getRowCount() {
    return data.size();
   }

   @Override
   public Object getValueAt(int row, int col) {
    return ((Vector) data.get(row)).get(col);
   }

   public String getColumnName(int col) {
    return columnNames[col];
   }
   public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
   }

   public void setValueAt(Object value, int row, int col) {
    ((Vector) data.get(row)).setElementAt(value, col);
    fireTableCellUpdated(row, col);
   }

   public boolean isCellEditable(int row, int col) {
    if (4 == col) {
     return true;
    } else {
     return false;
    }
   }

   public void insertData(Object[] values) {
    data.add(new Vector());
    for (int i = 0; i & lt; values.length; i++) {
     ((Vector) data.get(data.size() - 1)).add(values[i]);
    }
    fireTableDataChanged();
   }

   public void removeRow(int row) {
    data.removeElementAt(row);
    fireTableDataChanged();
   }
  }

  private static void createAndShowGUI() {
   JFrame frame = new JFrame("Abstract Table Demo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   AbstractTableDemo newContentPane = new AbstractTableDemo();
   frame.setContentPane(newContentPane);

   //Display the window.
   frame.pack();
   frame.setVisible(true);
  }

  public static void main(String[] args) {
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
     createAndShowGUI();
    }
   });
  }
 }