How is the Scimago journal ranking (Q1-Q4) defined? What does it mean that a journal is ranked Q1 according to Scimago Journal and Country Rank?
Q1 to Q4 refer to  journal ranking quartiles within a subdiscipline using the SJR citation index.

Thus, a first quartile journal (i.e., Q1) has an SJR in the top 25% of journals for at least one of its classified subdisciplines.

What is SJR?
The SJR is an index of weighted citations per article over a period of three years ( https://www.scimagojr.com/aboutus.php ). As far as citation based indicators of prestige go it is quite good. 
Citations and documents applied in this formula are based on the Scopus database.


  SCImago Journal Rank is a measure of scientific influence of scholarly journals that accounts for both the number of citations received by a journal and the importance or prestige of the journals where such citations come from. (Wikipedia)


How is ranking done? As noted, rankings are done at the subcategory/subdiscipline level. So  for example, journals are not ranked at the level of "psychology" or "chemistry". Rather they are ranked at the level of "analytical chemistry" or "clinical psychology". 

Note also that journals are often categorised in multiple subdisciplines, and the quartile can, and often does, vary based on the subdisscipline. 
The badge shown on scimago seems to take the most favourable ranking. So, for example, if the journal is ranked in the top quartile for at least one, it will have a badge as a Q1 journal.

Critical commentary:
In general, I think subdiscipline ranking based on SJR is superior to impact factors. It overcomes several biases in impact factor:


It uses a 3 year document window (impact factor uses 2): This is a better window across a broader range of disciplines.
It weights citations by prestige which can reduce the capacity for gaming and aligns within common sense that not all citations are created equally. I believe this also incorporates the idea that each publication only has so much prestige to give, so a citation from a paper with 100 references is worth less than a citation with 20 references.
It uses a more inclusive database of articles (i.e., Scopus) compared to Impact Factor which uses Web of Science.
Even after controlling for many of the above factors, differences in citation practices exist between disciplines, so within sub-discipline rankings are often fairer. Furthermore, often researchers and evaluators are trying to make decisions like where to send their best work or how to evaluate the quality of work of a researcher who operates in a particular subdiscipline. In this case, SJR within subdiscipline can be particularly useful.