| | |
Python GUI Programming
![]() | View First Unread |
Another look at PyQT's canvas:
python Syntax (Toggle Plain Text)
# pqt_drawtext2.py # playing with PyQT's QPainter # setPen, setBrush, setFont, drawRect and drawText import sys # simpler import from PyQt4.QtCore import * from PyQt4.QtGui import * class DrawText(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 300, 350, 150) self.setWindowTitle("Playing with PyQT's QPainter") def paintEvent(self, event): painter = QPainter() painter.begin(self) # PyQT has some color constants available # give the canvas blue background color painter.setBrush(QBrush(QColor("navy"))) painter.drawRect(event.rect()) # this will be the text color painter.setPen(QColor("orange")) # check the fonts available on your computer # for instance in C:\WINDOWS\Fonts painter.setFont(QFont('Comic Sans MS', 32)) # drawText (x, y, QString s) painter.drawText(45, 90, "Hello World") painter.end() app = QApplication(sys.argv) dt = DrawText() dt.show() app.exec_()
Should you find Irony, you can keep her!
Presenting data in the form of a table that can be sorted by column is slick, and relatively easy to do with PyQT's QTableView widget:
python Syntax (Toggle Plain Text)
# use PyQT's QTableView and QAbstractTableModel # to present tabular data (with column sort option) # tested with Python 3.1 and PyQT 4.5 # Henri import operator import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyWindow(QWidget): def __init__(self, element_list, header, *args): QWidget.__init__(self, *args) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 200, 460, 300) self.setWindowTitle("Sorting PyQT's QTableView") self.header = header self.mydata = element_list # create table table = self.createTable() # use vbox layout layout = QVBoxLayout() layout.addWidget(table) self.setLayout(layout) def createTable(self): # create table view tview = QTableView() # set table model tmodel = MyTableModel(self, self.mydata, self.header) tview.setModel(tmodel) # set minimum size of table tview.setMinimumSize(450, 300) # hide grid tview.setShowGrid(False) # set font font = QFont("Courier New", 8) tview.setFont(font) # hide vertical header vh = tview.verticalHeader() vh.setVisible(False) # set horizontal header properties hh = tview.horizontalHeader() hh.setStretchLastSection(True) # set column width to fit contents tview.resizeColumnsToContents() # set all row heights nrows = len(self.mydata) for row in range(nrows): tview.setRowHeight(row, 18) # enable sorting tview.setSortingEnabled(True) return tview class MyTableModel(QAbstractTableModel): def __init__(self, parent, mydata, header, *args): """ mydata is list of tuples header is list of strings tuple length has to match header length """ QAbstractTableModel.__init__(self, parent, *args) self.mydata = mydata self.header = header def rowCount(self, parent): return len(self.mydata) def columnCount(self, parent): return len(self.mydata[0]) def data(self, index, role): if not index.isValid(): return QVariant() elif role != Qt.DisplayRole: return QVariant() return QVariant(self.mydata[index.row()][index.column()]) def headerData(self, col, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole: return QVariant(self.header[col]) return QVariant() def sort(self, col, order): """sort table by given column number col""" self.emit(SIGNAL("layoutAboutToBeChanged()")) self.mydata = sorted(self.mydata, key=operator.itemgetter(col)) if order == Qt.DescendingOrder: self.mydata.reverse() self.emit(SIGNAL("layoutChanged()")) # the test data is from one of vegaseat's codes # so if there is a mistake don't blame Henri ... header = [' Symbol ', ' Name ', ' Atomic Weight ', ' Melt (K) ', ' Boil (K) '] # use numbers for numeric data to sort properly element_list = [ ('H', 'Hydrogen', 1.00794, 13.81, 20.28), ('He', 'Helium', 4.0026, 0.95, 4.216), ('Li', 'Lithium', 6.941, 453.7, 1615), ('Be', 'Beryllium', 9.0122, 1560, 3243), ('B', 'Boron', 10.811, 2365, 4275), ('C', 'Carbon', 12.011, 3825, 5100), ('N', 'Nitrogen', 14.0067, 63.15, 77.344), ('O', 'Oxygen', 15.9994, 54.8, 90.188), ('F', 'Fluorine', 18.9984, 53.65, 85.0), ('Ne', 'Neon', 20.1797, 24.55, 27.1), ('Na', 'Sodium', 22.98977, 371.0, 1156), ('Mg', 'Magnesium', 24.305, 922, 1380), ('Al', 'Aluminum', 26.9815, 933.5, 2740), ('Si', 'Silicon', 28.0855, 1683, 2630), ('P', 'Phosphorus', 30.9737, 317.3, 553), ('S', 'Sulfur', 32.066, 392.2, 717.62), ('Cl', 'Chlorine', 35.4527, 172.17, 239.18), ('Ar', 'Argon', 39.948, 83.95, 87.45), ('K', 'Potassium', 39.0983, 336.8, 1033), ('Ca', 'Calcium', 40.078, 1112, 1757), ('Sc', 'Scandium', 44.9559, 1814, 3109), ('Ti', 'Titanium', 47.88, 1935, 3560), ('V', 'Vanadium', 50.9415, 2136, 3650), ('Cr', 'Chromium', 51.996, 2130, 2945), ('Mn', 'Manganese', 54.938, 1518, 2235), ('Fe', 'Iron', 55.847, 1808, 3023), ('Co', 'Cobalt', 58.9332, 1768, 3143), ('Ni', 'Nickel', 58.6934, 1726, 3005), ('Cu', 'Copper', 63.546, 1356.6, 2840), ('Zn', 'Zinc', 65.39, 682.73, 1180), ('Ga', 'Gallium', 69.723, 302.92, 2478), ('Ge', 'Germanium', 72.61, 1211.5, 3107), ('As', 'Arsenic', 74.9216, 876.4, 876.3), ('Se', 'Selenium', 78.96, 494, 958), ('Br', 'Bromine', 79.904, 265.95, 331.85), ('Kr', 'Krypton', 83.8, 116, 120.85), ('Rb', 'Rubidium', 85.4678, 312.63, 961), ('Sr', 'Strontium', 87.62, 1042, 1655), ('Y', 'Yttrium', 88.9059, 1795, 3611), ('Zr', 'Zirconium', 91.224, 2128, 4683), ('Nb', 'Niobium', 92.9064, 2743, 5015), ('Mo', 'Molybdenum', 95.94, 2896, 4912), ('Tc', 'Technetium', 98, 2477, 4538), ('Ru', 'Ruthenium', 101.07, 2610, 4425), ('Rh', 'Rhodium', 102.9055, 2236, 3970), ('Pd', 'Palladium', 106.42, 1825, 3240), ('Ag', 'Silver', 107.868, 1235.08, 2436), ('Cd', 'Cadmium', 112.41, 594.26, 1040), ('In', 'Indium', 114.82, 429.78, 2350), ('Sn', 'Tin', 118.71, 505.12, 2876), ('Sb', 'Antimony', 121.757, 903.91, 1860), ('Te', 'Tellurium', 127.6, 722.72, 1261), ('I', 'Iodine', 126.9045, 386.7, 457.5), ('Xe', 'Xenon', 131.29, 161.39, 165.1), ('Cs', 'Cesium', 132.9054, 301.54, 944), ('Ba', 'Barium', 137.33, 1002, 2079), ('La', 'Lanthanum', 138.9055, 1191, 3737), ('Ce', 'Cerium', 140.12, 1071, 3715), ('Pr', 'Praseodymium', 140.9077, 1204, 3785), ('Nd', 'Neodymium', 144.24, 1294, 3347), ('Pm', 'Promethium', 145, 1315, 3273), ('Sm', 'Samarium', 150.36, 1347, 2067), ('Eu', 'Europium', 151.965, 1095, 1800), ('Gd', 'Gadolinium', 157.25, 1585, 3545), ('Tb', 'Terbium', 158.9253, 1629, 3500), ('Dy', 'Dysprosium', 162.5, 1685, 2840), ('Ho', 'Holmium', 164.9303, 1747, 2968), ('Er', 'Erbium', 167.26, 1802, 3140), ('Tm', 'Thulium', 168.9342, 1818, 2223), ('Yb', 'Ytterbium', 173.04, 1092, 1469), ('Lu', 'Lutetium', 174.967, 1936, 3668), ('Hf', 'Hafnium', 178.49, 2504, 4875), ('Ta', 'Tantalum', 180.9479, 3293, 5730), ('W', 'Tungsten', 183.85, 3695, 5825), ('Re', 'Rhenium', 186.207, 3455, 5870), ('Os', 'Osmium', 190.2, 3300, 5300), ('Ir', 'Iridium', 192.22, 2720, 4700), ('Pt', 'Platinum', 195.08, 2042.1, 4100), ('Au', 'Gold', 196.9665, 1337.58, 3130), ('Hg', 'Mercury', 200.59, 234.31, 629.88), ('Tl', 'Thallium', 204.383, 577, 1746), ('Pb', 'Lead', 207.2, 600.65, 2023), ('Bi', 'Bismuth', 208.9804, 544.59, 1837), ('Po', 'Polonium', 209, 527, 1235.15), ('At', 'Astatine', 210, 575, 610), ('Rn', 'Radon', 222, 202, 211.4), ('Fr', 'Francium', 223, 300, 950), ('Ra', 'Radium', 226.0254, 973, 1413), ('Ac', 'Actinium', 227, 1324, 3470), ('Th', 'Thorium', 232.0381, 2028, 5060), ('Pa', 'Proctactinium', 231.0359, 1845, 4300), ('U', 'Uranium', 238.029, 1408, 4407), ('Np', 'Neptunium', 237.0482, 912, 4175), ('Pu', 'Plutonium', 244, 913, 3505), ('Am', 'Americium', 243, 1449, 2880), ] app = QApplication(sys.argv) win = MyWindow(element_list, header) win.show() sys.exit(app.exec_())
Should you find Irony, you can keep her!
Exploring PyQT's QListView and QAbstractListModel. This little code pops up posssible words from word list as you type:
python Syntax (Toggle Plain Text)
# using PyQT's QListView and QAbstractListModel # to match partially typed word to words in list # make matching case insensitive # tested with Python 3.1 and PyQT 4.5 # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyWindow(QWidget): def __init__(self, words, *args): QWidget.__init__(self, *args) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 300, 320, 250) self.setWindowTitle("Match words with PyQT's QListView") self.words = words # create objects self.label = QLabel("Start typing to match words in list:") #self.edit = MyLineEdit() self.edit = QLineEdit() self.lmodel = MyListModel(self, self.words) self.lview = QListView() self.lview.setModel(self.lmodel) # layout layout = QVBoxLayout() layout.addWidget(self.label) layout.addWidget(self.edit) layout.addWidget(self.lview) self.setLayout(layout) # one key has been pressed in edit self.connect(self.edit, SIGNAL("textChanged(QString)"), self.update) def update(self): """ updates the list of possible completions each time key is pressed, use lower() to make things case insensitive """ p = str(self.edit.text()).lower() new_list = [w for w in self.words if w.lower().find(p)==0] self.lmodel.setAllData(new_list) class MyListModel(QAbstractListModel): def __init__(self, parent, words, *args): """ words is list of words """ QAbstractListModel.__init__(self, parent, *args) self.words = words def rowCount(self, parent=QModelIndex()): return len(self.words) def data(self, index, role): if index.isValid() and role == Qt.DisplayRole: return QVariant(self.words[index.row()]) else: return QVariant() def setAllData(self, new_list): """replace old list with new list""" self.words = new_list self.reset() # this is just test list of words state_list = [ 'Mississippi', 'Oklahoma', 'Delaware', 'Minnesota', 'Arkansas', 'New Mexico', 'Indiana', 'Louisiana', 'Texas', 'Wisconsin', 'Kansas', 'Connecticut', 'California', 'West Virginia', 'Georgia', 'North Dakota', 'Pennsylvania', 'Alaska', 'Missouri', 'South Dakota', 'Colorado', 'New Jersey', 'Washington', 'New York', 'Nevada', 'Maryland', 'Idaho', 'Wyoming', 'Maine', 'Arizona', 'Iowa', 'Michigan', 'Utah', 'Illinois', 'Virginia', 'Oregon', 'Montana', 'New Hampshire', 'Massachusetts', 'South Carolina', 'Vermont', 'Florida', 'Hawaii', 'Kentucky', 'Rhode Island', 'Nebraska', 'Ohio', 'Alabama', 'North Carolina', 'Tennessee' ] app = QApplication(sys.argv) win = MyWindow(state_list) win.show() sys.exit(app.exec_())
Should you find Irony, you can keep her!
One more simple way to present data in table form:
python Syntax (Toggle Plain Text)
# use PyQT's QTableWidget, QTableWidgetItem and setItem # to show data in simple table format # tested with Python 3.1 and PyQT 4.5 # Henri import sys # simplified import from PyQt4.QtCore import * from PyQt4.QtGui import * class MyTable(QTableWidget): def __init__(self, data, rows, cols): QTableWidget.__init__(self, rows, cols) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 200, 280, 180) self.setWindowTitle("Simple QTableWidget") self.data = data self.set_data() def set_data(self): """self.data is list of (fname, sname, age) tuples""" row = 0 for tup in self.data: col = 0 for item in tup: newitem = QTableWidgetItem(item) self.setItem(row, col, newitem) col += 1 row += 1 # fname, sname, age raw data for instance from file staff = """\ Frank, Marco, 27 Henri, Poulong, 34 Gisela, Lang, 19 Lance, Handy, 46""" # create list of (fname, sname, age) tuples data = [] for line in staff.split('\n'): fname, sname, age = line.split(',') data.append((fname.strip(), sname.strip(), age.strip())) app = QApplication(sys.argv) rows = 5 cols = 3 table = MyTable(data, rows, cols) table.show() sys.exit(app.exec_())
Should you find Irony, you can keep her!
Some options with a basic Tkinter window:
python Syntax (Toggle Plain Text)
# set position and size of a Tkinter window try: # for Python2 import Tkinter as tk except ImportError: # for Python3 import tkinter as tk #root = tk.Tk() root = tk.Tk(className="My Title") # sets title too # or give it your title this way #root.title("My Title") w = 300 h = 200 x = 50 y = 100 # use width x height + x_offset + y_offset (no spaces!) root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # make Tk window not resizable, also disables the maximize button #root.resizable(width=FALSE, height=FALSE) # or ... #root.resizable(0, 0) # or make root window full screen #root.state('zoomed') # give it a colorful frame frame = tk.Frame(root, bg='green') frame.pack(fill='both', expand='yes') root.mainloop()
No one died when Clinton lied.
For those of you who want experience vegaseat's sweet Tinter tkk example at:
http://www.daniweb.com/forums/post921416-25.html
on your Linux machines, in my case Ubuntu (Python 3.1 is not in the repository yet), here is an easy installation of Python 3.1:
Download ActivePython-3.1.0.1-linux-x86.tar.gz via
http://downloads.activestate.com/Act...nux-x86.tar.gz
from:
http://www.activestate.com/activepython/python3/
Extract to the Desktop
In the terminal change to the proper directory:
cd ~/Desktop/ActivePython-3.1.0.1-linux-x86/
Then run:
sudo ./install.sh
As install directory I entered something easy like:
/home/dell/python/3.1
The installation takes a short time. Now create a symbolic link:
sudo ln -s /home/dell/python/3.1/bin/python3.1 /usr/local/bin/python3.1
Now you are ready to enjoy Python 3.1
http://www.daniweb.com/forums/post921416-25.html
on your Linux machines, in my case Ubuntu (Python 3.1 is not in the repository yet), here is an easy installation of Python 3.1:
Download ActivePython-3.1.0.1-linux-x86.tar.gz via
http://downloads.activestate.com/Act...nux-x86.tar.gz
from:
http://www.activestate.com/activepython/python3/
Extract to the Desktop
In the terminal change to the proper directory:
cd ~/Desktop/ActivePython-3.1.0.1-linux-x86/
Then run:
sudo ./install.sh
As install directory I entered something easy like:
/home/dell/python/3.1
The installation takes a short time. Now create a symbolic link:
sudo ln -s /home/dell/python/3.1/bin/python3.1 /usr/local/bin/python3.1
Now you are ready to enjoy Python 3.1
•
•
•
•
# to run a scripts with Python3.1
# with the Geany IDE you can set 'Build'/'Set Includes and Arguments'
# 'Execute' to python3.1 "%f"
Last edited by sneekula; Aug 1st, 2009 at 7:09 pm.
No one died when Clinton lied.
One nice graphical way to select calendar date is with the calendar widget. Here is the PyQT example:
python Syntax (Toggle Plain Text)
# explore the PyQT QCalendarWidget widget # tested with Python 3.1 and PyQT 4.5 # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyCalendar(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(300, 300, 280, 220) self.setWindowTitle('Calendar') self.calendar = QCalendarWidget(self) self.calendar.setGridVisible(True) # use absolute layout (x_pos, y_pos) for widgets self.calendar.move(20, 20) self.connect(self.calendar, SIGNAL('selectionChanged()'), self.show_date) self.label = QLabel(self) self.label.move(120, 180) self.label2 = QLabel(self) self.label2.setGeometry(85, 200, 150, 20) # show initial date self.show_date() def show_date(self): date = self.calendar.selectedDate() # to get month/day/year like '8/13/2009' use ... s = "%s/%s/%s" % (date.month(), date.day(), date.year()) self.setWindowTitle(s) # test # date.toPyDate() gives year-month-day like '2009-8-13' self.label.setText(str(date.toPyDate())) # or you can use Qdate formatted string # to show something like 'Thursday August 13 2009' s2 = date.toString('dddd MMMM d yyyy') self.label2.setText(s2) app = QApplication(sys.argv) mc = MyCalendar() mc.show() app.exec_()
Last edited by bumsfeld; Aug 3rd, 2009 at 8:50 pm.
Should you find Irony, you can keep her!
Quick look at PyQT's QListWidget, commonly called 'list box'. Also shows how to create multiple buttons with the for loop. Here is short example:
python Syntax (Toggle Plain Text)
# pqt_listbox2.py # explore PyQT's QListWidget (list box) actions # tested with Python 3.1 and PyQT 4.5 # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyFrame(QWidget): def __init__(self, coffee_list, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 150, 420, 150) self.setWindowTitle('Things to do with QListWidget') self.coffee_list = coffee_list self.listbox = QListWidget() self.connect(self.listbox, SIGNAL("itemSelectionChanged()"), self.on_select) # use grid layout to position the widgets grid = QGridLayout(self) # addWidget(QWidget, row, column, rowSpan, columnSpan) grid.addWidget(self.listbox, 0, 0, 7, 2) # list of (btn_text, action_method) tuples btn_action = [ ("Load", self.lb_load), ("Sort", self.listbox.sortItems), ("Move Down", self.lb_down), ("Move Up", self.lb_up), ("Remove Line", self.lb_remove), ("Add Line", self.lb_add), ("Edit Line", self.lb_edit)] # the standard button is the QPushButton widget # create multiple buttons using the for loop row = 0 for text, action in btn_action: button = QPushButton(text) grid.addWidget(button, row, 2, 1, 1) self.connect(button, SIGNAL("clicked()"), action) row += 1 self.setLayout(grid) def lb_load(self): """list box load""" # clear any existing data first self.listbox.clear() self.listbox.addItems(self.coffee_list) # start with first line selected (highlighted) self.listbox.setCurrentRow(0) def lb_down(self): """move selected item down one list box line""" row = self.listbox.currentRow() if row < self.listbox.count() - 1: item = self.listbox.takeItem(row) self.listbox.insertItem(row + 1, item) self.listbox.setCurrentItem(item) def lb_up(self): """move selected item up one list box line""" row = self.listbox.currentRow() if row >= 1: item = self.listbox.takeItem(row) self.listbox.insertItem(row - 1, item) self.listbox.setCurrentItem(item) def lb_remove(self): """remove selected item from the list box""" row = self.listbox.currentRow() item = self.listbox.takeItem(row) del item def lb_add(self): """add new line to list box above current line""" row = self.listbox.currentRow() title = "Add new coffee" text, ok = QInputDialog.getText(self, title, title) if ok and not text.isEmpty(): self.listbox.insertItem(row, text) def lb_edit(self): """edit selected item via popup dialog window""" row = self.listbox.currentRow() item = self.listbox.item(row) if item is not None: title = "Edit the Coffee" text, ok = QInputDialog.getText(self, title, title, QLineEdit.Normal, item.text()) if ok and not text.isEmpty(): item.setText(text) def on_select(self): """an item in the listbox has been clicked/selected""" try: selected_name = self.listbox.selectedItems()[0].text() s = "selected = %s" % selected_name self.setWindowTitle(s) except: pass coffee_list = ['Irish Coffee (Whisky)', 'Brandy Coffee (Brandy)', 'English Coffee (Gin)', 'Calypso Coffee (Kahlua and Rum)', 'Jamaican Coffee (Tia Maria and Rum)', 'Shin Shin Coffee (Rum)', 'Baileys Irish Cream Coffee', "Monk's Coffee (Benedictine)", 'Seville Coffee (Cointreau)', "Witch's Coffee (Strega)", 'Russian Coffee (Vodka)', 'Australian Coffee (Cask Wine/Goon)', 'Corfu Coffee (Koum Quat liquor)', 'Kaffee Fertig (Prune Schnaps)', 'Caffe corretto (grappa)'] app = QApplication(sys.argv) frame = MyFrame(coffee_list) frame.show() sys.exit(app.exec_())
Should you find Irony, you can keep her!
Sometimes it's nice to attach label to entry widget. One way to do this is with class object:
Should work with Python2 versions too.
python Syntax (Toggle Plain Text)
# pqt_EntryLab1.py # create labeled data entry areas # tested with Python 3.1 and PyQT 4.5 # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyFrame(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 150, 300, 150) self.setWindowTitle('data entry with attached label') # label to the 'left' side is default self.e_name = LEditLab(self, "Enter your name:") self.e_age = LEditLab(self, "Enter your age: ") self.e_job = LEditLab(self, "Enter your job: ") # display result 2 different ways, label on top self.e_result2 = LEditLab(self, "Result: ", 'top') self.e_result = EditLab(self, "Result:", 'top') self.b_done = QPushButton("Done") # use a grid layout to position the widgets # note that the grid is centered on the frame grid = QGridLayout(self) # addWidget(QWidget, row, column, rowSpan, columnSpan) grid.addWidget(self.e_name, 0, 0, 1, 3) grid.addWidget(self.e_age, 1, 0, 1, 3) grid.addWidget(self.e_job, 2, 0, 1, 3) grid.addWidget(self.b_done, 3, 1, 1, 1) grid.addWidget(self.e_result2, 4, 0, 1, 3) grid.addWidget(self.e_result, 5, 0, 1, 3) self.setLayout(grid) # connect the button click signal to an action self.connect(self.b_done, SIGNAL("clicked()"), self.action) def action(self): name = self.e_name.text() age = self.e_age.text() job = self.e_job.text() s2 = "%s, %s, %s" % (name, age, job) self.e_result2.setText(s2) s = "%s\n%s\n%s\n" % (name, age, job) self.e_result.setText(s) class LEditLab(QWidget): """label QLineEdit data entry/display to the left or on top""" def __init__(self, parent, mytext=QString(), pos='left'): QWidget.__init__(self, parent) self.label = QLabel(mytext) self.edit = QLineEdit() label_pos = QBoxLayout.LeftToRight if pos == 'left' \ else QBoxLayout.TopToBottom layout = QBoxLayout(label_pos) layout.addWidget(self.label) layout.addWidget(self.edit) self.setLayout(layout) def text(self): """create QLineEdit() like method to get text""" return self.edit.text() def setText(self, text): """create QLineEdit() like method to set text""" return self.edit.setText(text) class EditLab(QWidget): """label QEdit data entry/display area to the left or on top""" def __init__(self, parent, mytext=QString(), pos='left'): QWidget.__init__(self, parent) self.label = QLabel(mytext) self.edit = QTextEdit() label_pos = QBoxLayout.LeftToRight if pos == 'left' \ else QBoxLayout.TopToBottom layout = QBoxLayout(label_pos) layout.addWidget(self.label) layout.addWidget(self.edit) self.setLayout(layout) def setText(self, text): """create QTextEdit() like method to set text""" return self.edit.setText(text) def getText(self): """ create method to get text use better syntax than QTextEdit() """ return self.edit.toPlainText() app = QApplication(sys.argv) frame = MyFrame() frame.show() sys.exit(app.exec_())
Should you find Irony, you can keep her!
Exampled code for PyQT's multiline text entry widget:
python Syntax (Toggle Plain Text)
# pqt_TextEdit1.py # explore PyQT's QTextEdit multiline text entry box # click right mouse button in edit area for popup menu # Henri import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MyFrame(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 50, 300, 180) self.setWindowTitle('QTextEdit() test') self.edit = QTextEdit(self) self.edit.append('just some text,\n you can append more') self.edit.append('well, here is more!!!') self.edit.append('click the right mouse button') self.edit.append('to get option popup menu\n') self.pbutton = QPushButton(self) self.pbutton.setText(' transfer text to label ') # label auto-adjusts to multiple lines self.label = QLabel(self) self.label.setText('label ...') # use grid layout manager grid = QGridLayout(self) # addWidget(QWidget, row, column, rowSpan, columnSpan) grid.addWidget(self.pbutton, 0, 0, 1, 1) grid.addWidget(self.edit, 1, 0, 1, 2) grid.addWidget(self.label, 2, 0, 1, 2) self.setLayout(grid) # bind the button clicked to action self.connect(self.pbutton, SIGNAL("clicked()"), self.action) def action(self): # get the text from self.edit text = self.edit.toPlainText() # put the text into self.label self.label.setText(text) app = QApplication(sys.argv) frame = MyFrame() frame.show() sys.exit(app.exec_())
Should you find Irony, you can keep her!
![]() |
Similar Threads
- Starting wxPython (GUI code) (Python)
- Starting Python (Python)
- Starting with GUI programming? (Python)
- python script help (Python)
- Python GUI Problem (Python)
- C Software Programming.. (C++)
- Frequently Used Python Commands (Python)
- starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Is there a function built-in into python for email?
- Next Thread: Help with printing offsets
| Thread Tools | Search this Thread |
accessdenied advanced apache application argv array beginner book builtin calculator change command converter countpasswordentry csv curved dan08 def dictionary dynamic edit enter event file float format function google homework import inches input jaunty java keyboard lapse library line lines linux list lists loop microphone mouse movingimageswithpygame mysqlquery newb number numbers numeric obexftp output parameters parsing path phonebook plugin prime programming py2exe pygame pyopengl python random recursion redirect remote return reverse scrolledtext session simple skinning software sprite statictext string strings syntax table terminal text textarea threading time tlapse trick tuple tutorial twoup ubuntu unicode unit urllib urllib2 variable voip wordgame wxpython







