Results 1 to 2 of 2

Thread: PyQT - Make integers and dates in QTableWidget properly sortable

  1. #1
    Join Date
    Mar 2017
    Posts
    3
    Platforms
    Windows

    Question PyQT - Make integers and dates in QTableWidget properly sortable

    Hi.
    I put the data into my QTableWidget tableView using a loop:
    Qt Code:
    1. for i in range(0, len(res)):
    2. self.tableView.setItem(i, 2, QTableWidgetItem(str(create_dataframe(res)[2][i])))
    3. self.tableView.setItem(i, 3, QTableWidgetItem(str(create_dataframe(res)[3][i])))
    To copy to clipboard, switch view to plain text mode 
    where
    Qt Code:
    1. create_dataframe(res)[2][i]
    To copy to clipboard, switch view to plain text mode 
    returns value of class 'int' and
    Qt Code:
    1. create_dataframe(res)[3][i]
    To copy to clipboard, switch view to plain text mode 
    returns value of class 'datetime.datetime' (like '2017-03-25 16:51:24'). The question is: how do I make this items properly sortable through
    Qt Code:
    1. self.tableView.setSortingEnabled(True)
    To copy to clipboard, switch view to plain text mode 
    , i.e. not as strings, but as integers and datetime respectively? I know that I should use setData and Qt.DisplayRole, but could you please give an example using this short piece of code?
    Thank you.

  2. #2
    Join Date
    Mar 2017
    Posts
    3
    Platforms
    Windows

    Default Re: PyQT - Make integers and dates in QTableWidget properly sortable

    OK, here is the answer I came up with by myself:

    Qt Code:
    1. self.tableView.setItem(i, 2, QTableWidgetItem(str(create_dataframe(res)[2][i])))
    2. it3.setData(Qt.EditRole, QVariant(create_dataframe(res)[3][i]))
    3. self.tableView.setItem(i, 3, it3)
    To copy to clipboard, switch view to plain text mode 

    I.e. there is no need to transform datetime value: it can be properly sorted in string form. As for integer values, I have to create an instance of QTableWidgetItem(), then use .setData with QVariant on it. After this I can setItem to the table.

Similar Threads

  1. Replies: 2
    Last Post: 8th February 2017, 06:51
  2. Replies: 0
    Last Post: 20th February 2016, 16:00
  3. Properly using QTableWidget and QTableWidgetItem
    By c0dehunter in forum Newbie
    Replies: 4
    Last Post: 27th October 2012, 16:38
  4. PyQt Populate a QTableWidget
    By n3wcr4zy in forum Newbie
    Replies: 0
    Last Post: 2nd March 2011, 09:20
  5. Why can't I make dynamic_cast work properly?
    By pir in forum General Programming
    Replies: 13
    Last Post: 18th July 2006, 17:17

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.